【问题标题】:How to detect if axios exceeds timeout如何检测axios是否超时
【发布时间】:2022-12-24 20:11:07
【问题描述】:

我目前正在处理 IPFS,我遇到了这个问题。

我有一个 IPFS 哈希列表,我想在最短的时间内呈现它,这就是为什么我需要在每个不同的时间找到最合适的网关。 我的想法是使用回避/循环为每个IPFS哈希随机选择列表中的网关,如果axios响应时间过长或捕获错误,它会调用自身(转到下一个网关)直到有合适的网关在其中响应时限。

但我不知道如何检测axios是否因为超时而退出或成功获取。

这是我的代码:

const publicGateway = [
    "https://ipfs.eth.aragon.network/ipfs/",
    "https://ipfs.io/ipfs/",
    "https://cloudflare-ipfs.com/ipfs/",
    "https://ipfs.fleek.co/ipfs/",
    "https://ipfs-infura.io/ipfs/",
    // ... more
]
export const findPublicGateWay = (ipfs) => {
    let url;

    const getGateway = async () => {
        const random = Math.floor(Math.random() * publicGateway.length);
        url = publicGateway[random] + ipfs;    // get random urls

        try {
            await axios({
                method: 'get',
                url: url,
                timeout: 2000,    // get out if the url does not respond after 2 seconds
            });

            /*
             * this block runs if the request exceeded timeout
             *
             * getGateway();    exceeds timeout: call itself
             * 
             */

            /*
             * this block runs if the request succeeded
             *
             * return url;    nothing: return url
             * 
             */


        } catch (error) {
            console.log(error);
            getGateway();    // catch error: call itself
        }
    }
    getGateway();
}

或者对于这种情况有更好的方法吗?

对不起,因为我的代码有点乱,谢谢大家,我是一名学习者,所以感谢您的所有回答。

【问题讨论】:

    标签: javascript axios ipfs


    【解决方案1】:

    我相信 catch 部分是处理超时错误的合适地方。此外,您应该检查 catch 部分中的 error.message 或 error.code。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-05
      • 2011-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多