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