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

Promise嵌套递归函数仅单次执行时才会resolve问题排查

问题分析与修复方案

你遇到的问题核心在于递归调用的Promise没有和外层Promise正确关联,导致外层Promise一直处于pending状态,永远不会触发then回调。

问题出在哪?

看你的reccursive函数:当depth < maxDepth时,你在Promise的executor函数里直接返回了reccursive(),但这个递归返回的Promise并没有和当前的外层Promise产生任何联系——当前外层Promise的resolve或reject根本没被调用!只有当depth === maxDepth时,你才调用了resolve(),但之前那些未触发resolve的Promise会一直挂着,导致整个Promise链无法完成。

举个具体场景,当maxDepth=1时:

  1. 第一次调用reccursive(),depth是0,进入递归,调用第二次reccursive()
  2. 第二次调用时depth等于1,触发resolve(),但这个resolve只完成了第二次的Promise
  3. 第一次调用的Promise的executor里从来没调用过resolve(),所以它一直处于pending状态,自然main里的then永远不会执行

修复后的代码

我们需要让外层Promise等待递归的Promise完成后再resolve,把递归调用的结果和外层Promise关联起来,这里提供两种简洁的修复方式:

方式一:在executor中关联递归Promise

let depth = 0;
const maxDepth = 1;
main();

function main() {
  reccursive().then(function(response) {
    console.log('all finished!');
  });
}

function reccursive() {
  return new Promise((resolve, reject) => {
    console.log('in recursive function');
    if (depth === maxDepth) {
      console.log('hit max depth');
      return resolve();
    }
    console.log('not max depth, increasing');
    depth++;
    // 关键:让当前Promise等待递归的Promise完成后再resolve
    reccursive().then(resolve);
  });
}

方式二:利用Promise链式调用简化逻辑

let depth = 0;
const maxDepth = 1;
main();

function main() {
  reccursive().then(() => {
    console.log('all finished!');
  });
}

function reccursive() {
  console.log('in recursive function');
  if (depth === maxDepth) {
    console.log('hit max depth');
    return Promise.resolve();
  }
  console.log('not max depth, increasing');
  depth++;
  return reccursive();
}

为什么这样能解决问题?

第二种写法里,每次递归都会返回新的Promise,形成一条完整的Promise链:当最后一次递归返回已resolved的Promise时,整个链会依次向上resolve,最终触发main里的then回调。

第一种写法里,当前Promise的resolve会等待递归的Promise完成后再执行,确保每一层Promise都能正确被resolve,不会出现悬而未决的pending状态。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:22:19