How Can I Call One Asynchronous Function In A Group Way?
I am sorry that I may not be able to describe this issue clearly. I will try: Now I have one asynchronous function which takes data and do something, e.g. function myFunction(num:
Solution 1:
You can accomplish this by breaking an array into chunks and processing the chunks using Array#map
and Promise#all
. You can then string the chunk processing together using Array#reduce
:
runChunkSeries([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 5, someAsyncFn);
// our placeholder asynchronous functionfunctionsomeAsyncFn(value) {
returnnewPromise((resolve) => {
setTimeout(resolve, Math.random() * 5000);
}).then(() =>console.log(value));
}
functionrunChunkSeries(arr, chunkSize, fn) {
returnrunSeries(chunk(arr, chunkSize), (chunk) =>Promise.all(chunk.map(fn)));
}
// Run fn on each element of arr asynchronously but in seriesfunctionrunSeries(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 chunkSizefunctionchunk(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;
}
Here's a working codepen.
Solution 2:
It's pretty simple using async
/await
actually:
(asyncfunction() {
var i = 0;
while (true) {
for (var promises = []; promises.length < 5; ) {
promises.push(myFunction(i++));
}
awaitPromise.all(promises);
}
}());
Solution 3:
I would use generators, or since you are using typescript, you could use es7 async/await syntax, and using lodash you could do something like this:
(asyncfunction(){
constiterations: number = 2;
constbatchSize: number = 5;
lettracker: number = 0;
_.times(iterations, asyncfunction(){
// We execute the fn 5 times and create an array with all the promisestasks: Promise[] = _.times(batchSize).map((n)=>myFunction(n + 1 + tracker))
await tasks // Then we wait for all those promises to resolve
tracker += batchSize;
})
})()
You can replace lodash with for/while loops if you wish.
Check https://blogs.msdn.microsoft.com/typescript/2015/11/03/what-about-asyncawait/
If i didn't understand correctly or there is something wrong with the code, let me know and i'll update the answer.
Post a Comment for "How Can I Call One Asynchronous Function In A Group Way?"