首页 > 解决方案 > 我可以等待异步操作循环在使用 TypeScript 的同步函数内完成吗?

问题描述

我有一个 foreach 循环,它执行许多接收数据并呈现表的异步函数。我想在所有异步之后调用第二个函数。foreach 循环中的调用已完成并呈现表格。

标签: typescriptasynchronousforeach

解决方案


是的你可以。让每一个你称之为 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
      }
    );

您可以通过替换forEachmap进一步简化此操作

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
      }
    );

推荐阅读