I have a function returning a Promise, without any awaits in body. What is the difference between those two snippets, if awaiting for them seems to work the same?
export async function getTags(
tagTypeId: number
): Promise<Tags[]> {
return getAllPages('/tags.json', {
tagTypeId
});
}
export function getTags(
tagTypeId: number
): Promise<Tags[]> {
return getAllPages('/tags.json', {
tagTypeId
});
}
Calling
const tags = await getTags(tag.typeId);
>Solution :
To answer your question What does ‘async in a function declaration’ do in a function without await? the answer is nothing.
Well, almost nothing.
If your function returns a value, it gets wrapped in a Promise object:
async function myFn() {
return 1
}
function myFn2() {
return 1
}
console.log(myFn()) // Promise, not 1
console.log(myFn2()) // 1
So in a nut shell adding async does two things:
- It allows you to use
awaitinside the function - It makes sure the function always returns a Promise object.
Also async functions will not throw Errors but instead return them as a rejected Promise object:
async function fn() {
throw new Error("My error")
}
console.log(fn()) // Promise (rejected)