【发布时间】:2019-02-14 08:53:09
【问题描述】:
我有一个 foreach 循环,它执行许多异步函数,这些函数接收数据并呈现一个表。 我想在所有异步之后调用第二个函数。 foreach 循环中的调用已完成并呈现表格。
【问题讨论】:
标签: typescript asynchronous foreach
我有一个 foreach 循环,它执行许多异步函数,这些函数接收数据并呈现一个表。 我想在所有异步之后调用第二个函数。 foreach 循环中的调用已完成并呈现表格。
【问题讨论】:
标签: typescript asynchronous foreach
是的,你可以。 让每一个你称之为 Promise 的动作。 将所有这些 Promise 保存为一个数组,然后调用 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
}
);
您可以通过将forEach 替换为map 来进一步简化此操作
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
}
);
【讨论】:
await 调用。