简体   繁体   English

向循环添加超时延迟

[英]Adding timeout delay to a loop

I'm in a need to update a firestore collection where each document requires an external API call.我需要更新一个 Firestore 集合,其中每个文档都需要一个外部 API 调用。 The API I'm using has a limit of 1 request per 10ms so without exceeding the quota limits Im trying to update my collections of 100's of elements我正在使用的 API 限制为每 10 毫秒 1 个请求,因此在不超过配额限制的情况下,我试图更新我的 100 个元素的 collections

async function timeout(ms:number) {
return new Promise(resolve => setTimeout(resolve, ms)); 
}

async function update(): Promise<void>{
const requests : bird<void>[] = [] 
const charts = await db.collection("charts5D").get()
charts.forEach(async(doc)=>{
    await timeout(1000).then(async()=>{
        // code that does a network request
        const request = req(options).then(async(response)=>{} 
        requests.push(request)
        
    })
})
return Promise.all(requests).then(()=>{
    console.log("kk")
}).catch((error)=>{
    console.log(error)
})} 

I added an artificially long delay of 1s to make sure the delays are working, however it seems that only the first time the loop runs the timeout is working, after that it still fires out the requests without any delay in effect and I get a Too Many Requests response from the api.我人为地添加了 1 秒的长延迟以确保延迟正常工作,但是似乎只有第一次循环运行超时才有效,之后它仍然会触发请求而没有任何延迟,我得到了一个 Too来自 api 的许多请求响应。 I tried simply doing await timeout(1000) and just adding the request code below but that still doesn't work我尝试简单地执行await timeout(1000)并在下面添加请求代码,但这仍然不起作用

The setTimeout functions adds a timer to your browser and executes the code inside after the specified milliseconds have passed. setTimeout 函数向您的浏览器添加一个计时器,并在经过指定的毫秒后执行其中的代码。

The problem here is that you are calling setTimeout(1000) on all of them, without any delay between.这里的问题是您在所有这些上调用 setTimeout(1000) ,之间没有任何延迟。 The delay only starts counting AFTER the setTimeout function is called.延迟仅在调用 setTimeout function 后开始计数。 So after 1 second, all your timers are up and they all resolve.所以 1 秒后,你所有的计时器都到了,它们都解决了。

To fix this, pass the index of your chart into the timeout function parameter, like this:要解决此问题,请将图表的索引传递给超时 function 参数,如下所示:

charts.forEach(async(doc, index)=>{
   await timeout(index*1000).then(async()=>{
      // code that does a network request
      const request = req(options).then(async(response)=>{} 
      requests.push(request)       
   })
})

So the first timer will be up in 1 second, the second timer in 2 seconds, etc.所以第一个计时器将在 1 秒内启动,第二个计时器将在 2 秒内启动,依此类推。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM