【问题标题】:I have groups of promises, how do I resolve each group "sequentially"?我有一组承诺,我如何“按顺序”解决每个组?
【发布时间】:2021-12-07 15:39:01
【问题描述】:

有一个名为 p-limit 的库是为此目的而构建的,但它是用 ESM 编写的,因此处理起来很麻烦。我想,实现我自己的有多难? So I came up with this implementation:

(async() => {
    const promisedAxiosPosts = _.range(0, 100).map(async(item, index) => {
      console.log(`${index}: starting`);
      return Promise.resolve();
    });

    let i = 0;
    for (const promisedAxiosPostGroup of _.chunk(promisedAxiosPosts, 10)) {
      console.log(`***********************
GROUP ${i}
SIZE ${promisedAxiosPostGroup.length}
***********************`);
      await Promise.all(promisedAxiosPostGroup);
      i++;
    }
  }

)().catch((e) => {
  throw e;
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

为什么不等待每个块完成后再继续下一个块?

我认为map 可能是罪魁祸首,但我不知道如何:它返回一个Promise<void>[];如果函数上是awaiting,它不会返回void[](不确定这是否是一回事)?

【问题讨论】:

  • @jcalz 哎呀,对不起。我以为是。一秒。
  • 您的整个方法在这里毫无意义,因为使用.map() 创建数组已经启动了所有异步操作。对它们中的大部分调用 Promise.all() 没有任何好处,因为它们已经在飞行中。
  • 您可以看到 pMap()mapConncurrent() 的实现,它们实际上调用了异步函数,因此一次运行的函数不超过 N。
  • 是的。如果函数 async (item, index) => { console.log(`${index}: starting`); return Promise.resolve(); } 是任务,则调用该函数会启动任务,然后通过 promise 等待其结果(或不这样做)不会影响其执行。
  • @Ry-wow。我无法相信我在不知道的情况下已经走了多远。谢谢

标签: javascript typescript async-await promise lodash


【解决方案1】:

为此,您需要返回一个函数,该函数在调用时会返回一个 Promise。该函数(thunk)延迟了实际操作的执行。

对数组进行分块后,调用当前分块中的函数,并使用Promise.all()等待所有的promise解决:

(async() => {
    const pendingPosts = _.range(0, 100).map((item, index) => {
      return () => { // the thunk
        console.log(`${index}: starting`);

        // a simulation of the action - an api call for example
        return new Promise(resolve => {
          setTimeout(() => resolve(), index * 300);
        });
      }
    });

    let i = 0;
    for (const pendingChunk of _.chunk(pendingPosts, 10)) {
      console.log(`***********************
GROUP ${i}
SIZE ${pendingChunk.length}
***********************`);
      await Promise.all(pendingChunk.map(p => p())); // invoke the thunk to call the action
      i++;
    }
  }

)().catch((e) => {
  throw e;
})
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-23
    • 1970-01-01
    • 2021-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-16
    • 2017-03-07
    相关资源
    最近更新 更多