簡體   English   中英

如何以組方式調用一個異步函數?

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

對不起,我可能無法清楚地描述這個問題。 我會嘗試:

現在我有一個異步函數,它接受數據並執行某些操作,例如

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

如果我必須使用此功能,我怎么能實現這一點? 我必須確保此函數的前五個調用已經解決,然后啟動后五個函數的調用。 我知道這看起來很奇怪,我試圖將我當前的問題抽象為這個數字問題。

感謝您的任何意見或想法。

您可以通過將數組分成塊並使用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

我會使用生成器,或者因為你使用的是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/

如果我沒有正確理解或代碼有問題,請告訴我,我會更新答案。

實際上使用async / await非常簡單:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM