为了账号安全,请及时绑定邮箱和手机立即绑定

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 关注
  • 227 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号