我有一个foreach循环,它执行许多异步函数,这些函数接收数据并呈现一个表。我想在所有异步之后调用第二个函数。foreach循环中的调用已完成,并且表被呈现。
发布于 2018-09-10 06:23:43
可以,停那儿吧。让每一个你称之为承诺的行动。将所有这些承诺保存为一个数组,然后调用Promise.all
const promises:Promise<{}>[] = [];
myWhatever.forEach(
item => {
const promise = new Promise<{}>(
(resolve, reject) => {
// Do something which ends up with resolve getting called
// at some point
}
);
promises.push(promise);
}
);
Promise.all(promises)
.then(
() => {
// Perform your post render tasks here
}
);
您可以通过用map替换forEach
来进一步简化这一过程
const promises = myWhatever.map(
item =>
new Promise<{}>(
(resolve, reject) => {
// Do something which ends up with resolve getting called
// at some point
}
)
);
Promise.all(promises)
.then(
() => {
// Perform your post render tasks here
}
);
https://stackoverflow.com/questions/52249016
复制相似问题