顺序URL请求Nodejs的最佳实践



我有一个我需要从API请求的URL列表,但是为了避免造成大量负载,我理想地希望用x的差距执行这些请求秒。所有请求完成后,某些逻辑不重要。

有很多方法可以解决,我已经实施了一对。

a)使用递归函数,该函数越过一个数组,该数组保存所有URL并在完成每个请求后调用自身,并且暂停已发生

b)在循环中设置每个请求的超时,并以增量延迟和返回承诺,并在使用Promise解决后。所有执行逻辑的其余部分等等。

这两个工作。但是,您说的是建议这样做的建议呢?这更多是一种学术性的问题,当我这样做以学习时,我宁愿避免使用库来抽象果汁的库。

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

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))
})

最后,遵循您的理解,使您最有意义的和您将在一个月内理解的内容。您可以阅读最好的一个是您更喜欢解决方案,在这里的性能并不重要。

您可以每个时期使用类似的东西。

如果您希望处理所有URL,即使某些URL失败了,您可以捕获失败的URL并在结果中挑选出来。

代码看起来像这样:

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);
  }
)

相关内容

最新更新