如何以组方式调用一个异步函数? [英] How can I call one asynchronous function in a group way?

查看:100
本文介绍了如何以组方式调用一个异步函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很抱歉,我可能无法清楚地描述此问题.我会尝试:

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: number):Promise<void> {
   return new Promise((resolve) => {
     console.log(num);
     return;
   });
} 

我想在一个组中打印5个数字(顺序无关紧要).重要的是,我想在上一组结束后打印下5个数字. 例如:

I want to print 5 numbers in a group (the order doesn't matter). What matters is that I want to print the next 5 numbers after the previous group finishes. For example:

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 make this happen if I have to use this function? I have to maker sure the first five calls of this function have been resolved and then spin up calls of the next five functions. I know this seems weird, I'm trying to abstract my current problem into this number problem.

谢谢您的任何评论或想法.

Thank you for any comments or idea.

推荐答案

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

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 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 .

这篇关于如何以组方式调用一个异步函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆