簡體   English   中英

按順序執行承諾映射

[英]Execute promises map sequentially

我編寫了一個在循環(映射)中調用的函數,並且該函數使用了 Promise。 現在,我希望該函數同步運行並在調用其下一個實例之前退出。

 function t1(){ let arr1 = [1,2,3,4,5]; return Promise.map(arr1, (val) =>{ const params = { "param1" : val1 }; return t2(params); }); } function t2(event){ return Promise.resolve() .then({ //do something //code doesn't reach here in sync manner. all five instance are invoked and then code reaches here for first instance and so on }) .then({ //promise chaining. do something more }) }

t2 被調用五次,但我希望每個實例只在實例返回值之前調用。 目前它的行為不是那樣,而是並行調用該函數五次。

由於項目限制,我無法使用 async/await。

您當前代碼的問題在於Promise.prototype.mapforEach一樣,不會等待在其中調用的異步函數完成。 (除非您使用await.then明確告訴解釋器這樣做,否則不會等待任何異步調用)

t1等待t2每次調用:

async function t1(){
  let arr1 = [1,2,3,4,5];
  const results = [];
  for (const val of arr1) {
    results.push(await t2(val));
  }
  return results;
}

或者,如果您想使用reduce而不是async / await

 const delay = () => new Promise(res => setTimeout(res, 500)); function t1(){ let arr1 = [1,2,3,4,5]; return arr1.reduce((lastProm, val) => lastProm.then( (resultArrSoFar) => t2(val) .then(result => [...resultArrSoFar, result]) ), Promise.resolve([])); } function t2(event){ return delay().then(() => { console.log('iter'); return event; }); } t1() .then(results => console.log('end t1', results));

或者,如果您需要將順序功能封裝在 t2 中,那么讓 t2 具有它生成的前一個 Promise 的半持久變量:

 const delay = () => new Promise(res => setTimeout(res, 500)); const t1 = () => { return Promise.all([1, 2, 3, 4].map(t2)); }; const t2 = (() => { let lastProm = Promise.resolve(); return (event) => { const nextProm = lastProm .catch(() => null) // you may or may not want to catch here .then(() => { // do something with event console.log('processing event'); return delay().then(() => event); }); lastProm = nextProm; return nextProm; }; })(); t1().then(results => console.log('t1 done', results));

(function loop(index) {
    const next = promiseArray[index];
    if (!next) {
        return;
    }
    next.then((response) => {
        // do Something before next
        loop(index + 1);
    }).catch(e => {
        console.error(e);
        loop(index + 1);
    });
})(0 /* startIndex */)

以下是將.reduce()與 async/await 結合使用時按順序運行 Promise 的樣子:

 async function main() { const t2 = (v) => Promise.resolve(v*2) const arr1 = [1,2,3,4,5]; const arr1_mapped = await arr1.reduce(async (allAsync, val) => { const all = await allAsync all.push(await t2(val) /* <-- your async transformation */) return all }, []) console.log(arr1_mapped) } main()

暫無
暫無

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

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