等待异步功能完成内部地图 [英] Waiting for async function to complete inside map

查看:82
本文介绍了等待异步功能完成内部地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下简单代码:

await Promise.all(arrayOfObjects.map(async (obj) => {
    return await someAsyncFunctionOnObj(obj);
}));

我的问题是, arrayOfObjects someAsyncFunctionOnObj ,执行时占用太多内存,因为循环不等待执行完成,而是在每一个上调用someAsyncFunctionOnObj(obj),等待全部解析,不需要按顺序,这会导致OOM崩溃。
我试过使用递归异步函数,这确实解决了订单问题,但仍导致OOM崩溃。

My problem is, arrayOfObjects, and someAsyncFunctionOnObj, take too much memory while executing, because the loop doesn't wait for the execution to finish, instead it calls someAsyncFunctionOnObj(obj), on each one, and waits till all are resolved, not necessary in order, this causes OOM crash. Iv'e tried using a recursive async function, which does solve the order problem, but still causes OOM crash.

我想要实现的流程是同步循环,意思是

The flow I want to achieve is a synchronous loop, meaning

await someAsyncFunctionOnObj(obj1); // wait for it to finish
await someAsyncFunctionOnObj(obj2); // wait for it to finish
...

有关如何正确实施的任何建议它?

Any suggestions on how to correctly implement it?

推荐答案

解决方案





Solution

async function queueAsyncFns(fns) {
  const values = [];

  await fns.reduce((previous, current, index, array) => {
    const thenable = index === 1 ? previous() : previous;
    return thenable.then(value => {
      values.push(value);
      return index === array.length - 1 ? current().then(value => values.push(value)) : current();
    });
  });

  return values;
}

示例

const anArray = [1, 2, 3];
const doSomething = async (id) => await fetch(`https://jsonplaceholder.typicode.com/users/${id}`).then(res => res.json());

queueAsyncFns(anArray.map((val) => () => doSomething(val))).then((val) => console.log(val));

上述功能可以解决您的问题。以下是它的作用的简要概述:

The above function should solve your issue. Here's a brief overview of what it does:

queueAsyncFns 接受一组返回调用结果的函数异步功能。通过调用每个函数并将Promise返回到reducer的下一次调用来减少此数组。每次迭代时,异步调用的值都会累积到一个名为 values 的数组中,该数组在迭代完所有项后返回。

queueAsyncFns accepts an array of functions that returns the result of calling an async function. This array is reduced by calling each function and returning the Promise to the next call of the reducer. With each iteration the value of the async call is accumulated into an array called values which is returned after all items have been iterated through.

通过在运行示例时查看瀑布图,可以直观地确定函数的准确行为。您可以看到每个网络呼叫仅在前一个网络呼叫完成后进行。

The accurate behaviour of the function can be determined visually by looking at the waterfall graph when running the example. You can see each network call is only made after the previous one has been completed.

这篇关于等待异步功能完成内部地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆