我怎样才能以组的方式调用一个asynchronous函数?

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

现在我有一个asynchronous函数,它接受数据并做一些事情,例如

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 

如果我必须使用这个函数,我怎么能做到这一点? 我必须确定这个function的前五个调用已经解决,然后调用下面五个函数的调用。 我知道这似乎很奇怪,我试图把我目前的问题抽象成这个数字问题。

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

你可以通过将数组拆分成块并使用Array#mapPromise#all处理块来实现这一点。 然后可以使用Array#reduce将string处理串起来:

 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 。

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

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

我会使用生成器,或者因为您使用的是打字稿,您可以使用es7asynchronous/等待语法,并使用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循环replacelodash。

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

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