【问题标题】:Can I wait for a loop of asynchronous operations to finish inside a synchronous function using TypeScript?我可以等待异步操作循环在使用 TypeScript 的同步函数内完成吗?
【发布时间】:2019-02-14 08:53:09
【问题描述】:

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

【问题讨论】:

    标签: typescript asynchronous foreach


    【解决方案1】:

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

    【讨论】:

    • 不过,这实际上并没有在同步函数内部完成。
    • 对不起,我没有意识到它必须是。我会改的。
    • 为了记录,这实际上是不可能的。一旦你开始使用异步的东西,它总是是异步的。当然你可以忽略 Promise,但它仍然在后台。你可以让它看起来像是同步的,但函数必须返回一个 Promise。
    • @jhpratt 我现在删除了await 调用。
    猜你喜欢
    • 2020-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-15
    • 2021-04-16
    相关资源
    最近更新 更多