Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What does 'async in a function declaration' do in a function without await?

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);

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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 await inside 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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading