首页 > 解决方案 > ES 6 Harmony 异步类方法链接

问题描述

这是一个简单的 JavaScript 示例:

class Test {
    constructor() {
        this.a = 0;
        this.b = 1;
    }

    doSomething = async () => {
        await this.doSomethingChained(1)
            .doSomethingChained(2)
            .doSomethingChained(3);
    };

    doSomethingChained = async (x) => {
        this.a = this.a + x;
        console.log('a is', this.a);
        return this;
    };
}

然后使用测试方法开始,但这并不重要

test('Vorgang erfassen', async t => {

    const t1 = new Test();
    await t1.doSomething();

控制台包含以下内容:

a is 1
TypeError: _this2.doSomethingChained(...).doSomethingChained is not a function

我不明白为什么this.a有效,但return this不是。我当然可以一个接一个地开始这个方法,但我喜欢使用链接。

doSomething = async () => {
    await this.doSomethingChained(1);
    await this.doSomethingChained(2);
    await this.doSomethingChained(3);
};

奇迹般有效。

a is 1
a is 3
a is 6

标签: javascriptasync-awaites6-class

解决方案


你可以像下面这样链接你的承诺:

doSomething = async () => {
    await this.doSomethingChained(1)
       .then(() => this.doSomethingChained(2))
       .then(() => this.doSomethingChained(3));
};

推荐阅读