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

如何确保链式调用中异步方法执行完成后再返回实例?

问题描述

我有一个类实例:

let myInstance = new MyObject();

该类定义如下:

export default class MyObject {
    constructor () {}

    methodOne () {
        // 执行操作……
        return this;
    }

    async methodTwo () {
        let db_query = await Connection.query('<数据库查询语句>');

        return this;
    }

    methodThree () {
        // 执行操作……
        return this;
    }

    // 其他方法
}

通过返回this,我可以对实例进行链式调用:

myInstance
    .methodOne()
    .methodTwo()
    .methodThree()

我该如何确保methodTwo在async/await解析完成后才返回this?
尝试如下写法无法解决问题:

let db_query = await Connection.query('<数据库查询语句>');

db_query
    .then(() => {
        return this;
    })

注意:myInstance本身被包裹在一个async/await方法中。

解决方案

你的methodTwo本身已经是async方法,它会自动返回一个Promise,当内部的await Connection.query执行完成后,才会把this作为Promise的resolve值返回。问题根本不在methodTwo内部,而是外部链式调用时没处理它返回的Promise,导致methodThree会在methodTwo的异步操作完成前就执行。

要让链式调用按顺序执行,有两种可行方式:

方式一:用await等待(推荐,因为上下文已是async方法)

直接在链式调用前加await,确保methodTwo执行完再调用methodThree:

await myInstance
    .methodOne()
    .methodTwo();
myInstance.methodThree();

或者更连贯的写法:

await myInstance
    .methodOne()
    .methodTwo()
    .then(instance => instance.methodThree());

方式二:用then衔接后续方法

如果不想用await,可以在methodTwo的Promise回调里调用methodThree,保持链式结构:

myInstance
    .methodOne()
    .methodTwo()
    .then(instance => {
        instance.methodThree();
        // 若要继续链式调用,返回instance即可
        return instance;
    });

至于你之前尝试的写法,完全是多余的——async方法里用了await后,db_query已经是Connection.query解析后的结果,不是Promise,再调用.then不会有任何效果。methodTwo内部只要在await之后直接return this就已经是正确的逻辑了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 17:40:22