Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call an async arrow function with await

If I define a function like this:

const getName = async () => await Promise.resolve('John');

When I try to call the getName function with async:

const name = await getName();
console.log(`Hi ${name}`);

It throws an error:

const name = await getName();
             ^^^^^

SyntaxError: await is only valid in async function

What I'm doing wrong?

like image 227
Carlos Avatar asked Oct 28 '18 22:10

Carlos


People also ask

Can you use async await with arrow function?

async is used to make a function asynchronous. It unlocks the use of await inside these functions. Using await in any other case is a syntax error. Notice the use of async keyword at the beginning of the function declaration. In the case of arrow function, async is put after the = sign and before the parentheses.

How do you call async await function?

async and await Inside an async function, you can use the await keyword before a call to a function that returns a promise. This makes the code wait at that point until the promise is settled, at which point the fulfilled value of the promise is treated as a return value, or the rejected value is thrown.

Can I use await async?

Note: The await keyword is only valid inside async functions within regular JavaScript code. If you use it outside of an async function's body, you will get a SyntaxError .


1 Answers

const getName = async () => await Promise.resolve('John');

In the above, you have an async function (the arrow function) which uses await inside.

This is fine (albeit pointless as you could return the promise directly).

Here:

const name = await getName();

You use await again, and while the function on the right-hand side does return a promise, the function it appears inside is not async so it is not valid.


Put it inside an async function and it will be fine:

const getName = async() => await Promise.resolve('John');

const init = async() => {
  const name = await getName();
  console.log(`Hi ${name}`);
};

init();

As mentioned though, making getName async and awaiting inside is just a needlessly complex set of nested promises and you could simplify:

const getName = () => Promise.resolve('John');

const init = async() => {
  const name = await getName();
  console.log(`Hi ${name}`);
};

init();
like image 190
Quentin Avatar answered Oct 04 '22 23:10

Quentin