web3.js中的连接超时

问题描述 投票:0回答:1

实例化Web3实例时,我可以传递提供程序选项,包括超时,例如:

const w3 = new Web3(new Web3.providers.HttpProvider('...', {timeout: 10e3}));

但是当我尝试连接到运行状况不佳的节点并检查其是否在侦听时,它似乎并不会影响isListening调用:

await w3.eth.net.isListening();

等待的时间超过了我指定的超时时间。

为什么会这样?我该如何强制在那里超时?

node.js ethereum web3 web3js
1个回答
0
投票

您可以使用Promise.race()获得与超时相关的第二个承诺。

await Promise.race([
    web3.eth.net.isListening(),
    new Promise(function(resolve, reject) {
        setTimeout(function() {
            reject("Time out");
        }, 10e3);
    }),
]);
© www.soinside.com 2019 - 2024. All rights reserved.