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?
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.
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.
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 .
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 await
ing 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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With