如何以组方式调用一个异步函数?

时间:2016-10-04 23:02:57

标签: javascript node.js asynchronous typescript async-await

对不起,我可能无法清楚地描述这个问题。我会尝试:

现在我有一个异步函数可以获取数据并执行某些操作,例如

function myFunction(num: number):Promise<void> {
   return new Promise((resolve) => {
     console.log(num);
     return;
   });
} 

我想在一组中打印5个数字(顺序无关紧要)。重要的是我想在上一组完成后打印下面的5个数字。 例如:

1, 2, 5, 4, 3, 6, 9, 8, 7, 10 ... is valid
7, 10, 1, 2, 3, 4, 5, 6, 8, 9 ... is not valid

如果我必须使用此功能,我该如何实现?我必须确保此函数的前五个调用已经解决,然后启动后五个函数的调用。我知道这看起来很奇怪,我试图将当前的问题抽象为这个数字问题。

感谢您的任何意见或想法。

3 个答案:

答案 0 :(得分:4)

您可以通过将数组分成块并使用Array#mapPromise#all处理块来实现此目的。然后,您可以使用Array#reduce

将块处理串在一起
runChunkSeries([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 5, someAsyncFn);

// our placeholder asynchronous function
function someAsyncFn(value) {
  return new Promise((resolve) => {
    setTimeout(resolve, Math.random() * 5000);
  }).then(() => console.log(value));
}

function runChunkSeries(arr, chunkSize, fn) {
  return runSeries(chunk(arr, chunkSize), (chunk) => Promise.all(chunk.map(fn)));
}

// Run fn on each element of arr asynchronously but in series
function runSeries(arr, fn) {
  return arr.reduce((promise, value) => {
    return promise.then(() => fn(value));
  }, Promise.resolve());
}

// Creates an array of elements split into groups the length of chunkSize
function chunk(arr, chunkSize) {
  const chunks = [];
  const {length} = arr;
  const chunkCount = Math.ceil(length / chunkSize);

  for(let i = 0; i < chunkCount; i++) {
    chunks.push(arr.slice(i * chunkSize, (i + 1) * chunkSize));
  }

  return chunks;
}

这是一个有效的codepen

答案 1 :(得分:1)

我会使用生成器,或者因为你使用的是typescript,你可以使用es7 async / await语法,并使用lodash你可以这样做:

(async function(){
  const iterations: number = 2;
  const batchSize: number = 5;
  let tracker: number = 0;
  _.times(iterations, async function(){
     // We execute the fn 5 times and create an array with all the promises
     tasks: Promise[] = _.times(batchSize).map((n)=> myFunction(n + 1 + tracker))
     await tasks // Then we wait for all those promises to resolve
     tracker += batchSize;
  })
})()

如果愿意,可以用for / while循环替换lodash。

检查 https://blogs.msdn.microsoft.com/typescript/2015/11/03/what-about-asyncawait/

如果我没有正确理解或代码有问题,请告诉我,我会更新答案。

答案 2 :(得分:1)

实际上使用async / await非常简单:

(async function() {
    var i = 0;
    while (true) {
        for (var promises = []; promises.length < 5; ) {
            promises.push(myFunction(i++));
        }
        await Promise.all(promises);
    }
}());