Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
42
rated 0 times [  44] [ 2]  / answers: 1 / hits: 13389  / 6 Years ago, sun, october 28, 2018, 12:00:00

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?


More From » async-await

 Answers
20

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




[#10577] Friday, October 26, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
travion

Total Points: 137
Total Questions: 96
Total Answers: 103

Location: India
Member since Wed, Aug 4, 2021
3 Years ago
travion questions
Mon, Dec 16, 19, 00:00, 5 Years ago
Sat, Oct 19, 19, 00:00, 5 Years ago
Fri, Sep 20, 19, 00:00, 5 Years ago
Wed, Nov 14, 18, 00:00, 6 Years ago
Sun, Oct 28, 18, 00:00, 6 Years ago
;