Trying to create chain of asynchronous methods in node.js Then is not working

Viewed 25

This question is a followup of an answer given here

I tried to create a minimal example to show what I mean when I say that then is not working, at the bottom of the page there are three tests, they should be tried one at a time.

'use strict';
//
class Client {
    constructor() {
        this.p = Promise.resolve();
    }
    method1(...args) {
        return this._chain(this._method1, ...args);
    }
    _method1() {
        this.prop = 1;
    }
    method2(...args) {
        return this._chain(this._method2, ...args);
    }
    _method2() {
        this.prop = 2;
    }
    someError(...args) {
        return this._chain(this._someError, ...args);
    }
    _someError() {
        throw Error('something went wrong');
    }
    _chain(fn, ...args) {
        this.p = this.p.then(() => fn.apply(this, args));
        return this;
    }
    then(a, b) {
        this.p = this.p.then(a, b);
        return this;
    }
    catch(fn) {
        this.p = this.p.catch(fn);
        return this;
    }
}

const client = new Client();

// testing chain (works)
async function testChain() {
    await client.method1().method2();
    console.log(client.prop);
}
testChain();

// testing then (does not work)
async function testThen() {
    await client
        .method1()
        .method2()
        .then((res) => console.log(res));
}
testThen();

// catch error (works)
async function testCatch() {
    await client
        .someError()
        .method1()
        .then((res) => console.log(res))
        .catch((err) => console.log(err));
}
testCatch();
0 Answers
Related