3 回答

TA貢獻(xiàn)2011條經(jīng)驗(yàn) 獲得超2個(gè)贊
創(chuàng)建一個(gè)承諾數(shù)組,然后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貢獻(xiàn)2021條經(jīng)驗(yàn) 獲得超8個(gè)贊
最好的解決方案是使用,Promise.all以便所有請(qǐng)求都可以并行進(jìn)行。這看起來(lái)像這樣。
function1() {
let arr = [1, 2, 3, 4, 5];
Promise.all(arr.map((num) => function2(num))).then(() => {
function3();
});
}
這將等到所有function2返回的 Promise都已解決,然后再調(diào)用function3.

TA貢獻(xiàn)1799條經(jīng)驗(yàn) 獲得超6個(gè)贊
也許是這樣的:
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);
添加回答
舉報(bào)