0
votes

Im trying to see if returning an empty block within .then() is the correct pattern when returning Promise.

Below is the method and how im returning code in the .then(). This code works but want to know the better way. Even the tslint is compling about this.

private async somexMethod(id: string, params?: someParams): Promise<void> {
    const url: string = "http://someendpointUri";
    const headers = await getMyHeadersAsync(id);

    // Here calling my API that returns the promise
    return this._myHttpClient.delete(url, { headers, params: someParams })
        .pipe(retryWhen(HttpUtil.someXPolicyForRetry))
        .toPromise() // this converts Observable<ResponseXyz> to Promise<ResponseXyz>

        // tslint:disable-next-line: no-empty
        .then(() => { }) // Is this the correct way to return for Promise<void> or .then(() => null) ?
        .catch(() => {
            // log error msg
        });
}

Here Observable is returned by the delete method as well as this function HttpUtil.someXPolicyForRetry. After converting to promise with toPromise(), how do I return the Promise ?

Is that calling .then() with empty block as above is the correct pattern to use or is there any other better way?. I also see that .then(() => null) as the other option but not sure if we have any other better way of returning Promise.

Please note that i want to maintain the same pattern in the codesnippet method like return this._myHttpClient.delete(..) and i dont want to change it to some other return new Promise(resolve, reject) or calling resolve().

1

1 Answers

0
votes

async functions always return a promise even if you don't return a promise explicitly.

Then in your code, as long as you don't return anything, it is always expected to be Promise<void>

private async somexMethod(id: string, params?: someParams): Promise<void> {
    const url: string = "http://someendpointUri";
    const headers = await getMyHeadersAsync(id);


    this._myHttpClient.delete(url, { headers, params: someParams }) // removed the return
        .pipe(retryWhen(HttpUtil.someXPolicyForRetry))
        .toPromise() // this converts Observable<ResponseXyz> to Promise<ResponseXyz>

        //.then(() => { }) // no need for this
        .catch(() => {
            // log error msg
        });
}

Here is a 4min read about async-await: https://medium.com/better-programming/should-i-use-promises-or-async-await-126ab5c98789