node.js – What is the difference between having or not having async keyword in the declaration of a Typescript method
There may be some minor implementation difference under the hood that I’m not aware of (and could differ by implementation), but functionally they do the same thing. Both functions return a Promise which resolves to a string.
Note that in the example given the first function is redundant. Which may have even been the source of the question in the first place.
This function is correct and returns a Promise:
function b(): Promise {
return Promise.resolve("method b");
}
To achieve the same functionality using async you don’t need the Promise:
async function a(): Promise {
return "method a";
}
An async function always implicitly returns a Promise. If the value being returned isn’t a Promise then it gets quietly wrapped in one. Which allows for things like this:
async function a(): Promise {
if (someCondition) {
return "method a";
}
return await someMethod(); // someMethod() itself returns a Promise
}
Notice how the return value technically on a fundamental level is “different” in that, depending on the condition, the function either returns a string or a Promise which resolves to a string. In the former case nothing asynchronous is happening at all.
Functionally this doesn’t matter because the engine will ensure the returned string is wrapped in a Promise so consuming code can always treat the operation as asynchronous.
Read more here: Source link
