ano*_*ran 2 javascript foreach promise async-await
我是async等待和承诺的初学者.我阅读了一些文章并观看了一些教程视频,但我仍然无法完全理解它.所以我有一个我现在正在处理的代码
}).then(function() {
var responseArray = []
[url1,url2,url3,url4].forEach((url)=>{
makeRequest(url)
}).then((response)=>{
responseArray.push(response)
})
return responseArray
})
Run Code Online (Sandbox Code Playgroud)
因此,如预期的那样,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
})
Run Code Online (Sandbox Code Playgroud)
任何人都可以帮我解决这个问题吗?
如果您使用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;
});
Run Code Online (Sandbox Code Playgroud)
或者,为了获得更好的性能,您可以使用 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;
});
Run Code Online (Sandbox Code Playgroud)
您需要将请求映射到承诺数组然后使用Promise.all:
.then(async () => {
const responseArray = await Promise.all(
[url1, url2, url3, url4].map(makeRequest)
);
})
Run Code Online (Sandbox Code Playgroud)
这将并行执行所有请求(除非您想限制带宽等,否则通常是您想要的).