8

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?

7
  • Your async function should return a Promise as opposed to waiting for it to resolve: return Promise.resolve('John');. Then your await getName(); call will have a Promise to wait for to be resolved. Commented Oct 28, 2018 at 22:35
  • @JimB. async function always return promises even when the function body doesn't. Commented Oct 28, 2018 at 22:37
  • Right. Ignore that. Commented Oct 28, 2018 at 22:37
  • 2
    It's telling you the error :await is only valid in async function I look like you are trying const name = await getName(); outside of an sync function. Commented Oct 28, 2018 at 22:37
  • 1
    @carlos, then you can't use await. You either need to wrap it in an async function or use getName.then() Commented Oct 28, 2018 at 22:41

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.