typescript - 我可以等待异步操作循环在使用 TypeScript 的同步函数内完成吗?
问题描述
我有一个 foreach 循环,它执行许多接收数据并呈现表的异步函数。我想在所有异步之后调用第二个函数。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
}
);
推荐阅读
- wait - 为什么在类中通知时不抛出 IllegalMonitorStateException
- r - 使用函数均值 [R] 时出现“参数不是数字或逻辑:返回 NA”错误
- xcode - Xcode source control won't commit
- python - 在训练时测量决策树的准确性
- javascript - 在 react-native 中将画布转换为图像数据
- javascript - 如果 monorepo 应该只包含一种语言项目?
- node.js - 在 aws lambda 上使用 webshot 时遇到问题
- javascript - 如何使用 localStorage 中的数据渲染 React 组件?
- html - 图像高度与宽度相同
- python - 如果条件
陈述是假的,我们不是必须跳过它吗?