javascript 如何对 forEach 函数进行异步等待
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/50328143/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to do async await on a forEach function
提问by anoop chandran
I'm a beginner in async await and promises. I read few articles and watch few tutorial videos but I am still not able to understand it completely. So I have a code that I'm working on right now
我是异步等待和承诺的初学者。我读了几篇文章,看了几篇教程视频,但我仍然无法完全理解它。所以我有一个我现在正在处理的代码
}).then(function() {
var responseArray = []
[url1,url2,url3,url4].forEach((url)=>{
makeRequest(url)
}).then((response)=>{
responseArray.push(response)
})
return responseArray
})
So as expected the responseArrayis returned empty. I need to make it wait until all the responses from each makerequest(url) is pushed to the responseArray.
This is my attempt
所以正如预期的那样responseArray返回空。我需要让它等到来自每个 makerequest(url) 的所有响应都被推送到 responseArray。
这是我的尝试
}).then(function() {
var responseArray = []
[url1,url2,url3,url4].forEach((url)=>{
async makeRequest(url)
}).then((response)=>{
await responseArray.push(response)
})
return responseArray
})
Can anyone help me fix this one?
谁能帮我解决这个问题?
回答by riwu
You need to map the requests to an array of promises then use Promise.all:
您需要将请求映射到一系列承诺,然后使用Promise.all:
.then(async () => {
const responseArray = await Promise.all(
[url1, url2, url3, url4].map(makeRequest)
);
})
This will execute all the requests in parallel (which is generally what you want unless you want to limit the bandwidth etc).
这将并行执行所有请求(这通常是您想要的,除非您想限制带宽等)。
If you want to execute them sequentially, there's a huge discussion on the best approach.
回答by Faly
You cannot wait for all the promises to be resolved if you use forEach. Use for .. ofinstead:
如果您使用forEach. 使用for .. of来代替:
}).then(async function() {
var arr = ['url1', 'url2', 'url3', 'url4'];
var responseArray = [];
for (url of arr) {
cont response = await makeRequest(url);
responseArray.push(response);
}
return responseArray;
});
Or, for a better performance, you can use Promise.all to launch all your requests in parallel:
或者,为了获得更好的性能,您可以使用 Promise.all 并行启动所有请求:
}).then(async function() {
var arr = ['url1', 'url2', 'url3', 'url4'];
var responseArray = await Promise.all(arr.map(function(url) {
return makeRequest(url);
}));
return responseArray;
});

