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

greetings函数可运行但返回Promise后.then()未执行,求助排查

问题分析与修复

你的代码核心问题是:第一次调用greetings()生成的Promise永远不会被resolve。

当y未达到数组长度时,你在setTimeout里递归调用greetings(),但每次递归都会新建一个独立的Promise。只有当y等于数组长度时,才会执行resolve——但这个resolve属于最后一次递归创建的Promise,和最初调用的那个Promise完全无关。最初的Promise一直处于pending状态,所以.then()里的逻辑永远不会触发。

修复方案1:用async/await + 循环(推荐)

这种方式不需要全局变量,逻辑更清晰,也避免了递归可能带来的问题:

const greetingDivs = [firstDiv, secondDiv, thirdDiv, fourthDiv, fifthDiv];

async function greetings() {
  for (const div of greetingDivs) {
    // 等待300ms
    await new Promise(resolve => setTimeout(resolve, 300));
    // 添加元素并滚动
    consoleOutput.appendChild(div).scrollIntoView(false, { behavior: 'smooth' });
  }
}

greetings().then(() => {
  console.log('hello');
});

修复方案2:修正递归逻辑

如果坚持用递归,需要让递归的Promise完成后再resolve当前的Promise,把整个Promise链串起来:

const greetingDivs = [firstDiv, secondDiv, thirdDiv, fourthDiv, fifthDiv];

let y = 0;

function greetings() {
  return new Promise((resolve, reject) => {
    if (y === greetingDivs.length) {
      resolve('done');
      return;
    }
    setTimeout(() => {
      consoleOutput.appendChild(greetingDivs[y]).scrollIntoView(false, { behavior: 'smooth' });
      y++;
      // 等待递归的Promise完成后,再resolve当前Promise
      greetings().then(resolve);
    }, 300);
  });
}

greetings().then(() => {
  console.log('hello');
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 18:48:38