Reputation: 14559
I'm trying to rewrite this Promise
-based code using async
\ await
:
public loadData(id: string): void {
this.loadDataAsync()
.then((data: any): void => {
// Do something with data
})
.catch((ex): void => {
// Do something with ex
});
}
public loadDataAsync(): Promise<any> {
// return Promise somehow
}
The rewritten code I have so far is:
public loadData(id: string): void {
let data: any;
try {
data = await this.loadDataAsync();
} catch(ex) {
// Do something with ex
}
// Do something with data
}
public async loadDataAsync(): Promise<any> {
// return Promise somehow
}
The problem is that I have to make loadData()
method async
since it has await in its body. Then, I have to return some Promise
from it, since async
methods must return a Promise
. But I need to maintain the API of loadData()
method and return void
.
How can I achieve this? How do you break a never ending need for making a method as async
when somewhere deep inside inner calls you're calling an async
method?
Upvotes: 1
Views: 1816
Reputation: 3745
Ideally if you can change the function declaration, just add the async
keyword to loadData
and use await
inside like so:
public async loadData(id: string): void {
let data: any;
try {
data = await this.loadDataAsync();
} catch(ex) {
// Do something with ex
}
}
If you are unable to change the loadData
function declaration, then you can just create an anonymous async
function inside, and then call await
within the anonymous function like so:
public loadData(id: string): void {
let data: any;
try {
data = (async () => { return await this.loadDataAsync() })();
} catch(ex) {
// Do something with ex
}
}
public async loadDataAsync(): Promise<any> {
return new Promise((resolve, reject) => {
// Logic goes here
resolve(data);
});
}
Whenever you use the await
keyword, the surrounding function must be marked as async
.
As was pointed out by the OP in the comments, in TypeScript it is best practice to mark the promise returning method with async
as well (see the loadDataAsync
function above), as this ensures the return type is always a promise. More info on that found here:
TypeScript Async / Await Tutorial
Upvotes: 3