顺序url请求nodejs的最佳实践

时间:2017-12-12 10:17:42

标签: javascript node.js promise

我有一个我需要从API请求的URL列表,但是为了避免造成大量负载,理想情况下我希望以x秒的间隔执行这些请求。一旦完成所有请求,就会产生一些无关紧要的逻辑。

有很多方法可以实现,我实施了一对。

A)使用一个遍历数组的递归函数,该数组包含所有url并在每个请求完成并且发生超时时自行调用

B)为循环中的每个请求设置超时,增量延迟并返回Promise,使用Promise.all解析后执行其余的逻辑等等。

这些都有效。但是,你会说推荐的方法是什么?这更像是一种学术性的问题,而且我这样做是为了学习,我宁愿避免使用一个抽象果汁的图书馆。

2 个答案:

答案 0 :(得分:1)

您的解决方案几乎完全相同。以为我会选择一点不同的方法。我会做出初步的承诺和睡眠承诺功能,然后我会把它们连在一起。

function sleep(time){
    return new Promise(resolve => setTimeout(resolve, ms));
}

ApiCall()
.then(sleep(1000))
.then(nextApiCall())...

或更多模块化版本

var promise = Promise.resolve()
myApiCalls.forEach(call => {
    promise = promise.then(call).then(() => sleep(1000))
})

最后,按照你的理解,最让你理解的是什么以及你将在一个月内理解什么。你最好读的是你喜欢的解决方案,性能在这里无所谓。

答案 1 :(得分:0)

你可以在每个时期使用throttle之类的内容。

如果您希望处理所有网址,即使有些网址失败,您也可以抓住失败的网址,然后在结果中选择它们。

代码看起来像这样:

const Fail = function(details){this.details=details;};
twoPerSecond = throttlePeriod(2,1000);
urls = ["http://url1","http://url2",..."http://url100"];
Promise.all(//even though a 100 promises are created only 2 per second will be started
  urls.map(
    (url)=>
      //pass fetch function to twoPerSecond, twoPerSecond will return a promise
      //  immediately but will not start fetch untill there is an available timeslot
      twoPerSecond(fetch)(url)
      .catch(e=>new Fail([e,url]))
  )
)
.then(
  results=>{
    const failed = results.map(result=>(result&&result.constuctor)===Fail);
    const succeeded = results.map(result=>(result&&result.constuctor)!==Fail);
  }
)
相关问题