Just wanted to understand correct approach using async/await when we return the value in async functions. what would be correct way to write code for async functions and return the value with promise ?
main.ts
private async customerResponse(data: any): Promise < any > {
const custObject: any = data;
Promise.resolve(custObject);
Or
return custObject;
}
Just wanted to understand correct approach using async/await when we return the value in async functions. what would be correct way to write code for async functions and return the value with promise ?
main.ts
private async customerResponse(data: any): Promise < any > {
const custObject: any = data;
Promise.resolve(custObject);
Or
return custObject;
}
Share
Improve this question
asked Aug 28, 2018 at 15:01
hussainhussain
7,14121 gold badges87 silver badges165 bronze badges
4
-
1
I'm not sure about typescript, but in JavaScript the
async
keyword already ensures that any immediately returned values are wrapped in a resolved Promise. – Paul Commented Aug 28, 2018 at 15:04 - Any particular reason you didn't take my word for it (especially since I provided a working link) on your other question? – Jared Smith Commented Aug 28, 2018 at 15:20
- example you provided was plicated to understand so i asked another question related to that issue. – hussain Commented Aug 28, 2018 at 16:01
-
@hussain It literally is just a async function that returns a string which
then
is printed to the console. I even added the return type annotation to show that the types check. How could I have made it simpler? – Jared Smith Commented Aug 28, 2018 at 18:15
1 Answer
Reset to default 11An async
function returns a promise. Moreover, you only need to use async
if you need the await
keyword. If you're not using await
, don't use async
.
The return value of an async
function is effectively unwrapped to a single level when using Promise.resolve
(I think this is part of Promise.resolve
functionality), so there is no difference between returning Promise.resolve(value)
or just returning value
(or Promise.resolve(Promise.resolve(value))
for that matter). That said, you should simply return the desired return value from async
functions and not worry about doing any additional wrapping.