Reputation: 1277
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?
Upvotes: 8
Views: 16496
Reputation: 944205
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();
Upvotes: 12