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

类与异步函数:确保类方法调用等待前序执行完成

如何确保类方法按顺序执行,等待前一个完成后再继续?

我有一个包含多个方法的类,每个方法要么调用async函数,要么处理其他方法生成的数据。如何确保调用类方法时,必须等待前一个方法执行完成后再继续?

以下是一个简单示例,会随机调用类的多个方法,每个方法执行耗时随机,我需要确保每个被调用的方法都等待前一个方法的执行结果:

class Test
{
  constructor()
  {
    //ignore the constructor, it's simplified for this example and does not play any role in the question
    const list = [...Array(~~(Math.random()*3)+3)].map(e=>~~(Math.random()*3+1));
    console.log("expected: " + list);
    list.forEach(f => this["method_" + f]());
  }
  method_1()
  {
    return new Promise(resolve => setTimeout(() => 
    {
      console.log(1);
      resolve("res 1");
    }, Math.random() * 1000 + 100));
  }
  method_2()
  {
    return new Promise(resolve => setTimeout(() => 
    {
      console.log(2);
      resolve("res 2");
    }, Math.random() * 1000 + 100));
  }
  method_3()
  {
    func3();
  }
}

new Test();

function func3()
{
  new Promise(resolve => setTimeout(() => 
    {
      console.log(3);
      resolve("res 3");
    }, Math.random() * 1000 + 100));
}

我无法使用then方法,因为每个方法不知道前一个执行的是哪个方法……或者我可以用?
我考虑添加一种队列机制,调用方法时将其加入队列,当前一个Promise resolved后再执行,但不确定这是否是最佳方案。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 22:36:31