【问题标题】:Given a list of async functions, how can I process them n at a time?给定一个异步函数列表,我如何一次处理它们?
【发布时间】:2018-08-08 04:15:51
【问题描述】:

JavaScript 提供了一种收集 Promise 列表的机制:

const tasks = [ fetch('a'), fetch('b'), fetch('c') ];

const results = await Promise.all(tasks); 

但是,如果我想执行所有任务,但只有 n 并发执行,该怎么办?

const results = await MorePromise.allWithConcurrency(2, tasks); // 2 at a time

JavaScript 是否提供这样的功能?如果没有,是否有任何强大的库可以做到?

【问题讨论】:

标签: javascript promise async-await


【解决方案1】:

您可以使用像 bluebird 这样的插件来实现它,它有一个 function 允许它:example here

const Promise = require('bluebird');
const _ = require('lodash');

let tasks = [...]; // over 10,000 items.

Promise.all(
  _(tasks).map(task => {
    return task.doAsyncThing();
  })
    .value();
);

Promise.map(
  tasks, 
  task => {
    return task.doAsyncThing();
  }, 
  { concurrency: 1000 }
);

您也可以自己创建一个函数来处理它。这是我自己编写的一个函数,它是可以改进的。

const resultPromises = [];

let nextToCall = 0;

let errorHappened = false;

/**
 * Function that get called when one promise got executed
 */
function callbackOnePromiseGotExecuted({
  error,
  result,
  allExecutedCallback,
  array,
}) {
  resultPromises.push(result);

  // Do nothing if an error got reported
  if (errorHappened) {
    return;
  }

  // Return the error
  if (error) {
    allExecutedCallback(null, resultPromises);

    errorHappened = true;

    return;
  }

  // Check if it was the last promise to execute
  if (resultPromises.length === array.length) {
    allExecutedCallback(null, resultPromises);

    return;
  }

  nextToCall += 1;

  // Stop if we already acalled everything
  if (nextToCall > array.length) return;

  // If it wasn't call a new promise
  array[nextToCall - 1].call()
    .then(ret => callbackOnePromiseGotExecuted({
      error: null,
      result: ret,
      allExecutedCallback,
      array,
    }))
    .catch(e => callbackOnePromiseGotExecuted({
      error: e,
      result: null,
      allExecutedCallback,
      array,
    }));
}

/**
 * Handle the call of multiple promise with concurrency
 */
function promiseWithConcurrencyCallback({
  array,
  concurrencyNumber,
  allExecutedCallback,
}) {
  for (let i = 0; i < concurrencyNumber; ++i) {
    array[nextToCall].call()
      .then(ret => callbackOnePromiseGotExecuted({
        error: null,
        result: ret,
        allExecutedCallback,
        array,
      }))
      .catch(e => callbackOnePromiseGotExecuted({
        error: e,
        result: null,
        allExecutedCallback,
        array,
      }));

    nextToCall += 1;
  }

}

function promiseWithConcurrency(array, concurrencyNumber) {
  return new Promise((resolve, reject) => {
    promiseWithConcurrencyCallback({
      array,
      concurrencyNumber,
      allExecutedCallback: (error, result) => {
        if (error) return reject(error);

        return resolve(result);
      },
    });
  });
}

const array = [
  () => new Promise((resolve) => resolve('01')),
  () => new Promise((resolve) => resolve('02')),
  () => new Promise((resolve) => resolve('03')),
  () => new Promise((resolve) => resolve('04')),
  () => new Promise((resolve) => resolve('05')),
  () => new Promise((resolve) => resolve('06')),
];

promiseWithConcurrency(array, 2)
  .then(rets => console.log('rets', rets))
  .catch(error => console.log('error', error));

编辑关于我对@Redu 帖子的评论

var ps      = [new Promise((resolve) => { console.log('A'); setTimeout(() => { resolve(1) }, 5000); }), Promise.resolve(2), Promise.resolve(3), Promise.resolve(4), new Promise((resolve) => { console.log('B'); setTimeout(() => { resolve(5) }, 5000); })],
    groupBy = (n,a) => a.reduce((r,p,i) => !(i%n) ? (r.push([p]),r) : (r[r.length-1].push(p),r),[]);

groupBy(2,ps).map(sps => Promise.all(sps).then(console.log));

正如您在我编辑的 sn-p 中看到的那样,console.log('A') 和 console.log('B') 立即显示。这意味着函数同时执行,然后每两个解析两个。因此,如果目的是限制对资源或其他东西的访问,那么您的解决方案将不起作用。他们仍将同时访问。

【讨论】:

    【解决方案2】:

    使用纯 JS ES6 怎么样..?

    var ps      = [Promise.resolve(1), Promise.resolve(2), Promise.resolve(3), Promise.resolve(4), Promise.resolve(5)],
        groupBy = (n,a) => a.reduce((r,p,i) => !(i%n) ? (r.push([p]),r) : (r[r.length-1].push(p),r),[]);
    
    groupBy(2,ps).map(sps => Promise.all(sps).then(console.log));
    .as-console-wrapper {
    max-height: 100% !important;
    }

    根据@Grégory NEUT 的正当评论,我还有两个选择,以防万一您有一组数据来调用承诺返回函数(我在这里使用bring 来模仿fetch)

    var bring   = (url,data) => new Promise((v,x) => setTimeout(v, ~~(Math.random()*500), data)); // echoes data in 0~500 ms
        urls    = ["url0", "url1","url2","url3","url4"],
        groupBy = (n,a) => a.reduce((r,u,i) => !(i%n) ? (r.push([u]),r) : (r[r.length-1].push(u),r),[]);
    
    groupBy(2,urls).reduce((p,sus,i) => i ? p.then(r => (console.log(`Here I am doing something with the fetched data from urls ${r}`),
                                                         Promise.all(sus.map(u => bring(u,u.replace(/[^\d]+/,""))))))
                                          : Promise.all(sus.map(u => bring(u,u.replace(/[^\d]+/,"")))), Promise.resolve())
                   .then(r => console.log(`Here I am doing something with the fetched data from urls ${r}`), e => console.log(e));

    或者也可以使用 spread 和 rest 运算符,例如;

    var bring   = (url,data) => new Promise((v,x) => setTimeout(v, ~~(Math.random()*500), data)); // echoes data in 0~500 ms
        urls    = ["url0", "url1","url2","url3","url4"],
        groupBy = (n,a) => a.reduce((r,u,i) => !(i%n) ? (r.push([u]),r) : (r[r.length-1].push(u),r),[]),
        seqPrms = (sus,...suss) => Promise.all(sus.map(u => bring(u,u.replace(/[^\d]+/,""))))
                                          .then(r => (console.log(`Here I am doing something with the fetched data from urls ${r}`),
                                                      suss.length && seqPrms(...suss)),
                                                e => console.log(e));
    
    seqPrms(...groupBy(2,urls));

    【讨论】:

    • 在你的解决方案中,所有的函数都被调用,然后两个两个解析。但重要的是它们都被同时执行。例如,使用这个:var ps = [new Promise((resolve) =&gt; {console.log('A'); setTimeout(() =&gt; resolve(1), 5000);}), Promise.resolve(2), Promise.resolve(3), Promise.resolve(4), Promise.resolve(5)];。因此,如果 OP 想要两个两个地做某事,它是行不通的。你只需两两解决。
    • @Grégory NEUT 否。它将完美地运行承诺两个两个,您可以在.then(console.log) 部分应用您的逻辑,例如每对.then(doSomething)。 doSomething 将在这对中的最后一个完成时被调用。
    • @Grégory NEUT 我知道了。我最初的想法是处理手头的承诺并分组处理他们的then 阶段。你知道 Fetch API 有很多链接的then() 阶段。然而……你是对的。我添加了两种替代解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-28
    • 2021-02-22
    • 1970-01-01
    • 1970-01-01
    • 2012-05-14
    • 2021-12-13
    • 2020-10-04
    相关资源
    最近更新 更多