最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

node.js - How to Timeout After Calling Await on an async function in JavascriptNode - Stack Overflow

programmeradmin0浏览0评论

I have an async function web3.eth.isListening() that causes the following statement to be stuck forever if there is an error:

await web3.eth.isListening()

How can we let the above await statement timeout after 10 seconds, and do a console.log to show that an error has occurred?

I have an async function web3.eth.isListening() that causes the following statement to be stuck forever if there is an error:

await web3.eth.isListening()

How can we let the above await statement timeout after 10 seconds, and do a console.log to show that an error has occurred?

Share Improve this question edited Mar 17, 2023 at 20:24 TylerH 21.1k79 gold badges79 silver badges114 bronze badges asked Nov 2, 2018 at 21:43 NyxynyxNyxynyx 63.9k163 gold badges507 silver badges856 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 9

You can use Promise.race() to provide a second Promise that is tied to a timeout.

await Promise.race([
    web3.eth.isListening(),
    new Promise(function(resolve) {
        setTimeout(function() {
            console.log('Timed out');
            resolve();
        }, 10000);
    }),
]);
发布评论

评论列表(0)

  1. 暂无评论