You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular中递归函数执行完成后调用函数的异常问题排查

问题分析与解决方案

代码问题点

  • Promise提前触发resolve:resolve('func1 completed')写在setTimeout外部,会在func1刚创建Promise时就立即执行,完全没等setTimeout里的异步逻辑和递归操作完成,导致then里的func2提前触发。
  • 递归Promise未关联当前流程:当len > 0时调用递归的func1,只是简单调用后挂了空的then(),没有把递归的Promise和当前Promise的resolve绑定,递归的异步流程和当前Promise完全脱节,无法同步完成状态。

修正后的代码

ngOnInit() {
  this.func1(this.myArray.length).then(() => {
    this.func2();
  }).catch(err => console.error(err));    
}

func1(len: number) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      console.log('in function func 1 ---  ', this.myArray.length);
      if (len > 0) {
        this.myArray.pop();
        // 等待递归的func1完成后,再resolve当前Promise
        this.func1(this.myArray.length).then(() => {
          resolve('func1 completed');
        }).catch(reject);
      } else {
        // 递归终止,直接resolve当前Promise
        resolve('func1 completed');
      }
    }, 1000);
  });
}

func2() {
  console.log('in function func  2');
}

修正逻辑说明

  1. 将resolve移到setTimeout内部,确保只有当setTimeout里的逻辑执行完毕,才会触发Promise的完成状态。
  2. 递归调用func1时,等待递归返回的Promise完成后再调用当前Promise的resolve,让整个递归的异步流程形成完整的链式结构,只有所有递归步骤全部执行完成,最外层的Promise才会resolve,进而触发func2执行。

内容的提问来源于stack exchange,提问作者usersam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 10:32:38