簡體   English   中英

在最后一個承諾解析為遞歸承諾時捕獲

[英]Capture when the last promise resolves in a recursive promise

我正在調用一個函數,該函數本質上返回一個用列表或什么都不解決的promise。 然后,我為列表中的每個項目調用相同的函數。 最終,所有人都將一事無成。 我只想在所有問題解決后再運行一些代碼,但無法弄清楚該怎么做。

為了簡化我的問題,我創建了這個示例。 我只能控制遞歸函數。 將所有的promise保存到一個數組,並將其傳遞給以下示例中的Promises.all():

 function randomLowerInt(int) { return parseInt(Math.random() * int); } function smallerArray(size) { const arr = []; const smallerSize = randomLowerInt(size); for (let i = 0; i < smallerSize; i++) { arr.push(i); } return arr; } function createPromise(arrLength) { const secnds = parseInt(Math.random() * 20) * 1000; const timeCreated = new Date().getTime(); const p = new Promise(res => { setTimeout(() => { const timeResolved = new Date().getTime(); res({ timeCreated, timeResolved, arrLength }); }, secnds); }); return p; } function recursive(arr) { arr.forEach(() => { createPromise(arr.length).then(({ timeCreated, timeResolved, arrLength }) => { // console.log({ // timeCreated, // timeResolved // }); const smallerArr = smallerArray(arrLength); recursive(smallerArr); }); }); } recursive([1, 2, 3, 4, 5]); const promises = []; function recursive2(arr) { arr.forEach(() => { const p = createPromise(arr.length).then(({ timeCreated, timeResolved, arrLength }) => { const smallerArr = smallerArray(arrLength); recursive2(smallerArr); return ({ timeCreated, timeResolved }); }); promises.push(p); }); } recursive2([1, 2, 3, 4, 5]); console.log('Waiting...'); Promise.all(promises).then(vals => console.log(vals)); 

不起作用,因為Promise.all()將在數組完全填充之前被調用。

如果預期的結果是只有 timeCreatedtimeResolved在單個對象的屬性可以聲明數組作為一個變量, .push()中的值到所述陣列return Promise.all().map()代替.forEach()並將結果記錄在鏈接的.then()

該模式可以用for..of .reduce()async/awaitfor..of循環或其他模式for..of

let res = []
function recursive(arr) {
  return arr.map((promise) => {
    return createPromise(arr.length).then(({ timeCreated, timeResolved, arrLength }) => {
      console.log({ timeCreated, timeResolved });
      res.push({ timeCreated, timeResolved });
      const smallerArr = smallerArray(arrLength);
      return Promise.all(recursive(smallerArr));
    });
  });
}

Promise.all(recursive([1, 2, 3, 4, 5])).then(() => console.log(res));

暫無
暫無

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

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