【问题标题】:Retrying failed attempts with NodeJS/ES6使用 NodeJS/ES6 重试失败的尝试
【发布时间】:2017-12-18 20:16:22
【问题描述】:

前言:我是 C++ 背景的新手。

我正在编写一个使用公共 npm 库来请求几组数据的 NodeJS 应用程序。数据源速率限制请求,在一些极端情况下会达到这些速率限制。当达到这些限制时,API 只会在处理更多请求之前返回“Rate Limit Exceeded”几秒钟。

当我收到数据时,我尝试使用.map() 解析它。但是,当超过速率限制时,整个应用程序就会崩溃,因为map() 仅适用于数组,并且“超出速率限制”消息只是一个简单的对象。

if (message.message === 'Rate limit exceeded') { //This check doesn't work btw
    console.log('There was a problem parsing data from the server: ' + err);
    return;
    }

    var items = data.map(item => ({
        time: new Date(item[0] * 1000),
        low: item[1],
        high: item[2],
        open: item[3],
        close: item[4],
        volume: Number(item[5])
    }));

    for(var i = 0; i < items.length; i++)
        dataStore.push(items[i]);

我想通过检测“超出速率限制”消息来解决此问题,等待几秒钟,然后重试。

根据我目前的理解,setTimeout() 将是一个很好的候选者,但我不明白如何让它递归地工作。本质上,我希望它每五秒重新请求一次数据,直到数据被正确处理。

TL;DR:我希望一个函数使用setTimeout() 递归调用自身,直到它正确接收数据;或者如果有更好的方法来实现这一点,我会全力以赴。

【问题讨论】:

    标签: javascript node.js


    【解决方案1】:

    您可以在这里做的是使用setInterval() 并继续每隔 n 秒检查一次。获取数据后,您可以使用clearInterval() 退出setInterval()

    请注意,我在此上下文中使用 jQuery,因为我不确定您是否使用任何特定的 NPM 包来请求数据。

    let retryAfter = 10000; //10 seconds
    
    setInterval(function fetchData() {
      $.get('//api.jsonbin.io/b/5a3823a38aaf400a97709c43', (data) => {
      
        // Keep on retrying
        console.log(data);
    
        // If you get the data, just exit the setInterval
        if(data) {
          clearInterval(fetchData);
        }
      });
    }(), retryAfter); 
    
    //() brackets here is to execute the function without the first 10 sec delay
    &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;

    到目前为止,在这个例子中,我的setInterval() 将只运行一次,因为它首先获取数据。但在您的示例中,它将一直运行,直到您收到数据为止。

    另外,我不能建议您应该如何比较您的错误消息,因为我不确定返回错误消息的 API 是 JSON 还是纯文本形式。这取决于您如何根据响应数据类型比较错误消息。

    【讨论】:

      【解决方案2】:

      你可以这样做 if(Array.isArray(data) === false) return;

      https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-06-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多