2

I'm attempting to call nested async functions inside a class, if that's even possible with the new async / await feature in 2017.

Heres some example code, which I'm running with NodeJS v7.7.2:

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
class Counter {
    async run() {
        await this.one();
        await this.two();
        await this.three();
        return new Promise(function (resolve) {
        });
    }
    async one() {
        console.log('one');
        return new Promise(function (resolve) {
        });
    }
    async two() {
        console.log('two');
        return new Promise(function (resolve) {
        });
    }
    async three() {
        console.log('three');
        return new Promise(function (resolve) {
        });
    }
}
exports.Counter = Counter;
let counter = new Counter();
counter.run();

What I'm expecting to happen is this code to print one two three

However, it only prints one

It seems that the subsequent calls to this.two() and this.three are not being made. Been trying to debug this problem for a couple of days.

1
  • 1
    What are all these new Promises doing there that you never resolve? Commented May 13, 2017 at 8:26

1 Answer 1

7

Your promises never resolve:

    return new Promise(function (resolve) {
    });

There should be some call to resolve in there. But if you were just trying to make the async function return a promise, then don't create a promise at all: async functions always return a promise, and this already happens when the first await is encountered. The promised value is whatever you return with return. So don't return a promise, but nothing (i.e. undefined) or some other value that you would like the promise to resolve to.

Just to illustrate, in browsers that support async (e.g. Firefox 52+), the following snippet will output one, two, three:

class Counter {
    async run() {
        await this.one();
        await this.two();
        await this.three();
    }
    async one() {
        console.log('one');
    }
    async two() {
        console.log('two');
    }
    async three() {
        console.log('three');
    }
}
let counter = new Counter();
counter.run();

Sign up to request clarification or add additional context in comments.

2 Comments

You don't even need Promise.resolve, just return nothing. Or don't return anything at all if there's no result value.
Explicitly returning a promise from a function/method marked async is superfluous, as any return value will automatically be wrapped by a promise (that's what async does).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.