How can I call one asynchronous function in a group way?

I'm sorry that I cannot clearly describe this problem. I'll try:

Now I have one asynchronous function that takes data and does something, for example.

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

I want to print 5 numbers in a group (order doesn't matter). The important thing is that I want to print the next 5 numbers after the end of the previous group. For instance:

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

How can I do this if I need to use this function? I have to be sure that the first five calls to this function will be resolved, and then the next five functions will be called. I know this seems weird, I'm trying to distract my current problem from this number problem.

Thanks for any comments or ideas.

+4
3

, Array#map Promise#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.

+4

, , typescript, async/await es7, 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;
  })
})()

lodash /while, .

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

- , , .

+1

, async/await :

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

Source: https://habr.com/ru/post/1656747/


All Articles