亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Node.js:調用遞歸函數的后處理結果

Node.js:調用遞歸函數的后處理結果

Helenr 2022-01-07 10:46:04
我需要處理延遲調用外部服務器的對象數組,將所有結果收集到數組中并對它們進行后處理。示例在這里:(async () => {  const serverOperation = () => new Promise(resolve => setTimeout(() => resolve(), 2000));  const myOtherFunction = results => console.log('results', results);  const objectsArray = [{}, {}, {}];  const results = [];  const myFunc = async arr => {    const el = arr.shift();    if (!el) {      // finish of calling recursive function      return;    }    // some big server operation    const result = await serverOperation();    results.push(result);    // need to wait for some time    setTimeout(async () => {      console.log(Date.now());      await myFunc(arr);    }, 3000);  };  await myFunc(objectsArray);  await myOtherFunction(results);  // <= postprocessing results})();問題是:myOtherFunction在我得到所有結果之前調用了該函數。我的問題是:如何對所有處理結果進行后處理?
查看完整描述

1 回答

?
明月笑刀無情

TA貢獻1828條經驗 獲得超4個贊

您可以使用超時 Promise來延遲函數的執行,而不是setTimeout.


您的代碼的問題是,即使您將async函數傳遞給setTimeout它也不會停止當前函數的執行。setTimeout只會將任務移動到微任務隊列并執行傳遞給它的函數。但它不會導致您的父函數停止,因為傳遞給的函數setTimeout不會立即調用 - 它稍后會在不同的時間、不同的地方調用。


(async () => {

  const serverOperation = () => new Promise(resolve => setTimeout(() => resolve('server op'), 2000));

  const myOtherFunction = results => console.log('results', results);

  const objectsArray = [{}, {}, {}];

  const results = [];

  

  // used for delaying operations

  const timeoutPromise = () => new Promise(resolve => setTimeout(() => resolve(), 3000));


  const myFunc = async arr => {

    const el = arr.shift();


    if (!el) {

      // finish of calling recursive function

      return;

    }


    // some big server operation

    const result = await serverOperation();


    results.push(result);


    // need to wait for some time

    await timeoutPromise();

    

    console.log(Date.now());

    

    await myFunc(arr);

  };


  await myFunc(objectsArray);

  await myOtherFunction(results);  // <= postprocessing results

})();


查看完整回答
反對 回復 2022-01-07
  • 1 回答
  • 0 關注
  • 189 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號