async function getSomething(parameter) {
...
}
function myFunction() {
const params = [param1, param2, ...]
const results = []
let i = 0
params.forEach((param) => {
getSomething(param).then((result) => results[i++] = result)
})
console.log(results)
}
结果为空,因为 for 中的调用是异步的,尚未执行。
如何等待for循环中的所有Promise都被解决?
您可以利用
Promise.all
对您有利。它将允许您等待一系列承诺得到解决。
参考以下代码:
async function getSomething(parameter) {
// Your business logic here
}
async function myFunction() {
const params = [param1, param2, ...];
const results = [];
const promises = params.map(async (param) => { // Generate a array of promises
const result = await getSomething(param);
results.push(result);
});
await Promise.all(promises); // Wait all the promises in the array to get resolved
console.log(results); // Output after all promises gets resolved
}