Skip to content
Advertisement

How to write better async/await + promise code?

So this is how it looks.

function async doAction() {
    await this.waitForData();
    // do some other things after data loads
    // when data loads it's available in this.data
}

function waitForData() {
    if (!this.promise) {
        this.promise = new Promise(res => this.promiseResolve = res);
        return this.promise;
    }
    else {
        return Promise.resolve(this.data);
    }
}

function loadData(data) {
    //some things
    this.data = data;

    if (this.promiseResolve) {
        this.promiseResolve(this.data);
    }
}

It works pretty fine, doAction waits for data load and then action starts. But it’s pretty much code, is there a better way to do it?

Advertisement

Answer

There’s some bugs with concurrent calls or calls in unexpected sequence. I would do

function waitForData() {
    if (!this.promise) {
        this.promise = new Promise(res => this.promiseResolve = res);
    }
    return this.promise;
}

function loadData(data) {
    //some things
    this.data = data;

    if (this.promiseResolve) {
        this.promiseResolve(this.data);
        this.promiseResolve = null;
    } else {
        this.promise = Promise.resolve(this.data);
    }
}

But other than that, yes this is the way to go for connecting two independent things by promises.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement