-1

I am developing a web application using Angular 8. I have a problem using JavaScript with an asynchronous function. I have created a service that has a public method: this method examines a condition that can vary over time and in one case (true) it updates its data with a response to an HTTP call; in the other case (false) it returns the data it already has. Here is a code example:

private date; // My date

getMyDate() {

    if(my_boolean_condition) {

        this.http.post(this.myUrl, JSON.stringify(this.myInputData)).toPromise().then((data: any) => {
            this.date = data;

            return this.date;
        }

    } else {
        return this.date;
    }

}

I know perfectly that something is wrong with this code, but I don't understand what. If a client (for example an Angular component) calls my getMyDate() method, the return value is however undefined. What I want is for the method to always return a value different than undefined, whether it makes the HTTP call or doesn't.

wishyouwerehere
  • 163
  • 1
  • 3
  • 8

1 Answers1

0

Yes, first return this.date; is wrong because it's returning to a anonymous function passed to thenable. The correct way is to use async/await:

async getMyDate() {

    if(my_boolean_condition) {

        let response = await this.http.post(this.myUrl, JSON.stringify(this.myInputData)).toPromise();
        return response;
    } 

    return this.date;

}

EDIT

Check more: https://javascript.info/async-await

Isaac Bruno
  • 254
  • 1
  • 8