0

I'm trying to use async/await for a very basic promise, but I'm getting the error: SyntaxError: await is only valid in async function. However, I believe I'm using await for an async function.

function getNumber(mult) { return new Promise((resolve, reject) => { resolve(10); }).then((val) => { return new Promise((resolve, reject) => { resolve(val * mult) //reject("Error"); }).then((val2) => val2); }).catch((err) => { return err; }) } const calculate = async (x) => await Promise.resolve(getNumber(x)) const val = await calculate(2) 
3
  • 2
    const val = await calculate(2) must be in an async function. Commented Aug 30, 2021 at 20:28
  • 2
    There's a lot of superfluous code here, in addition to the problem that your await calculate isn't in an async function as the error explains. calculate could be simply getNumber(x) as the extra async/await and Promise.resolve don't do anything, the many new Promises and thens seem pointless. I'm not sure I understand what you're hoping to accomplish. Commented Aug 30, 2021 at 20:30
  • 3
    Why are you using promises in this situation? Commented Aug 30, 2021 at 20:34

2 Answers 2

1

You cannot have the initial function with an await at the top level... just a modification.

function getNumber(mult) { return new Promise((resolve, reject) => { resolve(10); }).then((val) => { return new Promise((resolve, reject) => { resolve(val * mult) //reject("Error"); }).then((val2) => val2); }).catch((err) => { return err; }) } const calculate = (x) => Promise.resolve(getNumber(x)); const val = calculate(2).then(resp => { console.log('do something with response: ', resp) })

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

Comments

0

To only focus on why you're getting that error, the await in await calculate(2) isn't in an asynchronous function. If you can make it asynchronous function then do that but if not then you can use the .then() function like below:

calculate(2).then(val => { //Your code here } 

5 Comments

The fix is correct but I think the reason is wrong. The error isn’t due to calculate not being an async function. I'm pretty sure you can await any value
This will of course mean that val is now a promise that resolves to a number, instead of simply being a number. So you may also need to change the code that calls this function.
@evolutionxbox Yes, you can await any value, and if it's not a promise it will be converted to one. The problem is that you can only use await inside an async function.
That’s correct @evolutionxbox however the issue is that the calculate function and the await keyword isn’t inside an asynchronous function
Ah, good catch @David Knipe. I’ve edited my answer to a more complete solution that allows you to use the returned value. Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.