3 回答
TA贡献2011条经验 获得超2个赞
创建一个承诺数组,然后Promise.all使用async/await.
// async/await - create an array of promises
// from function2, then await until Promise.all has
// fully resolved/rejected
async function1() {
let arr = [1, 2, 3, 4, 5];
const promises = arr.map((num) => function2(num));
await Promise.all(promises);
function3();
}
function2(number) {
return axios.post('/internal-url/action/' + number);
}
function3() {
console.log('reloading data...');
/* DB call to reload data */
console.log('data is reloaded');
}
TA贡献2021条经验 获得超8个赞
最好的解决方案是使用,Promise.all以便所有请求都可以并行进行。这看起来像这样。
function1() {
let arr = [1, 2, 3, 4, 5];
Promise.all(arr.map((num) => function2(num))).then(() => {
function3();
});
}
这将等到所有function2返回的 Promise都已解决,然后再调用function3.
TA贡献1799条经验 获得超6个赞
也许是这样的:
const arr = [1, 2, 3, 4, 5];
let index = 0;
const answers = [];
(function loop() {
const value = arr[index];
function2(value).then(res => {
answers.push(res);
});
index++;
if (index < arr.length) {
loop();
}
})();
function3();
console.log(answers);
添加回答
举报