简体   繁体   English

我如何让 javascript 循环在开始下一次循环之前等待循环的每次迭代完成?

[英]How do i make javascript loop wait for each iteration of loop to finish before starting the next?

I have a loop that gets iterated through 1000 times where each iteration makes a request and then prints the result of that request.我有一个循环迭代 1000 次,每次迭代都会发出一个请求,然后打印该请求的结果。

Similar to below.类似于下面。

let start = console.log(Date.now())
for (i = 0; i < 1000; i++) {
    request.then(data => {
        console.log(Date.now() - start)
    })
}

This however results in the first request taking much longer to be completed then if there was just 1 iteration of the loop.然而,如果循环只进行 1 次迭代,则这会导致第一个请求需要更长的时间才能完成。

with i < 1000:当 i < 1000 时:

5860
...

with i < 1:当我 < 1:

220,
...

For the aim of this script however, I want to wait for each result to be received before starting the next iteration of the loop.然而,为了这个脚本的目的,我想在开始下一次循环迭代之前等待接收到每个结果。

If you want to stick with the ES5 way of handling Promises, you could use the following approach:如果您想坚持使用 ES5 处理 Promise 的方式,您可以使用以下方法:

const start = console.log(Date.now())

// Create a instantly resolved promise
for (let i = 0, p = Promise.resolve(); i < 1000; i++) {
  // append new promise to the chain
  p = p.then(() => request()
       .then(() => console.log(Date.now() - start));
}

If you can use ES6 methods, you could write this using the async/await pattern like so:如果您可以使用 ES6 方法,您可以使用async/await模式编写它,如下所示:

const asyncLoop = async () => {
  const start = console.log(Date.now())

  for (let i = 0; i < 1000; i++) {
    const data = await request();
    console.log(Date.now() - start);
  }
}

asyncLoop();

The chance that you really want to make the requests one after the other is actually pretty small though, so in case you want to make the request simultaneously, but do something after all of them resolved, you can use Promise.all(...)您真正想要一个接一个地发出请求的机会实际上很小,所以如果您想同时发出请求,但在所有请求都解决后做某事,您可以使用Promise.all(...)

const start = console.log(Date.now())
const requests = [request1, request2, ...];

Promise.all(requests)
       .then(() => console.log(Date.now() - start));

You can use the async-await pattern here.您可以在此处使用 async-await 模式。 You can achieve this by changing the code您可以通过更改代码来实现此目的

 async function iteration() { let start = console.log(Date.now()) for (let i = 0; i < 1000; i++) { const data = await httpRequest() console.log(Date.now() - start) } } async function httpRequest() { return new Promise((resolve, reject) => { request.then(data => { //Do anything you want to do with data resolve(data) }).catch(error => { console.error(`Error in request`) reject(error) }) }) }

Explanation:解释:

  1. I have moved the request code in a separate function httpRequest and this function will return promise on success我已将请求代码移动到单独的函数httpRequest 中,此函数将在成功时返回承诺
  2. I called httpRequest in for loop using await keyword, now loop will wait till the request is completed我使用 await 关键字在 for 循环中调用了httpRequest ,现在循环将等待请求完成
  3. I have also wrapped for loop code in function since you can only use await inside an async function我还在函数中包装了 for 循环代码,因为您只能在 async 函数中使用 await

暂无
暂无

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

相关问题 如何让 Javascript 循环等待现有迭代完成,然后再开始下一个? - How do I make a Javascript loop wait for existing iteration to finsih before starting the next? 如何使循环等待db promise完成,然后再继续下一次迭代? - How do I make for loop wait for db promise to finish before it continues to next iteration? Javascript:等待循环中的函数在下一次迭代之前完成执行 - Javascript: wait for function in loop to finish executing before next iteration 如何等到 promise 完成后再开始 JavaScript 中的“无限”for 循环的下一次迭代 - How to wait until a promise is completed before starting the next iteration of an “infinite” for loop in JavaScript .each()循环在开始之前等待另一个循环结束 - .each() loop wait for another loop to finish before starting 如何进行循环以等待元素,然后再进行下一次迭代 - How to make for loop wait for an element before moving to next iteration 异步for循环:如何使for循环等待函数完成? - Asynchronous for loop: how do I make the for loop wait for function to finish? 如何延迟内部for循环并使外部for循环等待utill内部循环将完成迭代? - How can I delay inner for loop and make outer for loop to wait utill inner loop will finish iteration? 等待函数完成,然后再继续执行$ .each函数中的下一个循环 - wait for the function to finish before continuing to the next loop in a $.each function 我正在尝试在开始下一个循环之前在每个循环中完成动画 - I'm trying to finish an animation in an each loop before starting the next one
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM