My node.js script is able to successfully connect to the Web3 provider when both the private key (using truffle-privatekey-provider) and the provider host URL are correct.

let privateKey = ...,
    providerUrl = ...
const provider = new PrivateKeyProvider(privateKey, providerUrl)
const web3 = new Web3(provider)

try {
    await web3.eth.net.isListening();
} catch (e) {
    console.log('Error connecting to provider')

Problem: However when the provider host URL is incorrect, the above code does not throw any errors and simply gets stuck in the await statement.

Is there a way to know when there is an issue connecting to the provider host?

  • I think you could add a timeout function to the await, but I think that's about it.
    – GrandFleet
    Nov 2, 2018 at 18:44
  • @GrandFleet What timeout duration will you suggest? 10 seconds?
    – Nyxynyx
    Nov 2, 2018 at 20:44
  • 10 seconds makes sense, but considering how crypto is starting to take off in smaller communities without traditionally banking options and with slower internet it may be a good idea to have a 30 second timeout duration.
    – GrandFleet
    Nov 2, 2018 at 20:47
  • @GrandFleet How can we use setTimeout together with web3.eth.net.isListening()? Cant seem to figure out the code
    – Nyxynyx
    Nov 2, 2018 at 21:33
  • I'm not exactly sure how to do that is setTimeout, but if you were to use setTimeout I think you could convert your try catch to then catch for promises. See stackoverflow.com/questions/49813405/…, but I don't know the answer off the top of my head.
    – GrandFleet
    Nov 2, 2018 at 23:37

1 Answer 1


You can use Promise.race to get the result of the first returned promise, where the first promise is your web3.eth.net.isListening() and the second is an error thrown after a timeout.

// Returns promise or throws error after timeout reached
const timeout = (prom, time) => Promise.race([prom, new Promise((_r, rej) => setTimeout(rej, time))]);

try {
  // Allow isListening to run for 10 seconds
  await timeout(web3.eth.net.isListening(), 10000);
} catch (e) {
  console.log('Error connecting to provider')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.