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

如何让setTimeout中的函数全部执行完毕后再执行后续代码?

问题原因

你的代码中setTimeout属于异步宏任务,调用fun()时不会等待内部定时器执行完成,就会直接往下执行console.log("end"),所以会出现先输出end,再每隔1秒输出!的错误结果。

修复方案

只需要两步修改,给异步执行逻辑包裹Promise,再用await等待执行完成即可:

  • 修改B类的fun方法,返回Promise,所有!输出完成后触发resolve
  • 修改C类的f方法为async方法,等待fun的Promise执行完成后再输出end

完整修复后代码

class A {
  constructor() {
    this.cnt = 5;
  }

  real() {
    this.cnt--;
    console.log("!");
  }

  getCnt() {
    return this.cnt;
  }
}

class B {
  constructor() {
    this.a = new A();
  }
  fun() {
    return new Promise((resolve) => {
      const run = () => {
        if (this.a.getCnt() > 0) {
          this.a.real();
          setTimeout(run, 1000);
        } else {
          resolve();
        }
      }
      run();
    })
  }
}

class C {
  constructor() {
    this.b = new B();
  }
  async f() {
    await this.b.fun();
    console.log("end");
  }
}
var c = new C();
c.f();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 19:36:02