Syntaxerror await is only valid in async function

Are you dealing with syntaxerror await is only valid in async functions error message?

Yet, you are struggling with how you can resolve this error. Then, you must keep on reading!

This article discusses the solutions for await is only valid in async functionsSyntaxError that usually encounters in JavaScript and NodeJs.

What is “async” function?

An async function is a function that returns a Promise and allows you to use the await keyword within its body.

The await keyword makes the function pause its execution and wait for a resolved Promise before it continues.

What is “syntaxerror: await is only valid in async functions”?

The syntaxerror await is only valid in async function, indicating that you are trying to use the await keyword outside of an async function.

For example:

const result = await someAsyncTask();
console.log(result);

Output:

SyntaxError: await is only valid in async functions and the top level bodies of modules

This error means that you have attempted to use the await keyword in a non-async function or in a context where it is not allowed.

What is top-level bodies of modules?

Top-level bodies of modules or top-level awaits mean that we can use the await keyword outside of an asynchronous function as long as it is used in a module.

Why does the “await is only valid in async functions” SyntaxError occurs?

The error message syntaxerror await is only valid in async function occurs when you are trying to use the await keyword outside of an asynchronous function.

In JavaScript, the await keyword is used to pause the execution of an asynchronous function until a promise is resolved or rejected.

However, you can only use await inside a function that is marked with the async keyword.

Here are some of the scenarios wherein you can face this error message.

Scenario 1: Calling await outside of an async function

For example:

function myFunction() {
  await someAsyncOperation();
}

To fix this error, you need to convert the surrounding function into an async function or call an existing async function from within it.

Solution 1: Convert the function into an async function

async function myFunction() {
  await someAsyncOperation();
}

Note: Please be cautious that when you convert a function to be asynchronous, it will always return a promise.

Therefore, if you are using that function in other parts of your code, ensure to upgrade your code correctly.

Solution 2: Call an existing async function from within a non-async function


✅ async function existingAsyncFunction() {
  await someAsyncOperation();
}

function myFunction() {
  existingAsyncFunction();
}

Scenario 2: Using await in a regular callback function

For example:

setInterval(() => {
  await someAsyncOperation();
}, 2000);

To fix the issue, you need to wrap the callback function inside an async function in order to use the await properly.

Solution: Wrap the callback function inside an async function to use await properly

✅ setInterval(async () => {
  await someAsyncOperation();
}, 2000);

Scenario 3: Using await in a synchronous function

For example:

function syncFunction() {
  const result = await someAsyncOperation();
  return result;
}

To fix the issue, make the enclosing function async or handle the asynchronous operation differently using promises and then()

Solution 1: Make the function async

async function syncFunction() {
const result = await someAsyncOperation();
return result;
}

Solution 2: Handle the asynchronous operation using promises and then()

✅ function syncFunction() {
return someAsyncOperation().then(result => {
// Handle the result
return result;
});
}

How to fix “syntaxerror await is only valid in async function”?

To fix the syntaxerror: await is only valid in async function error message, you can wrap the await keyword into an async function. The await keyword can only be used inside an async function.

Syntaxerror await is only valid in async function in Node.js

If you want to use the await keyword at the top level of your Node.js application, ensure that you set the type attribute to the module in your package.json file.

If you do not already have a package.json file, you can create one by using the following command:

 npm init -y 

If you already have one, you don’t have to do this, okay😉

To modify the package.json file located in the main directory of your project, open it and update the type attribute to module.

{
  "type": "module",
  // input other settings
}

Finally, you can now use the top-level await in your Node.js code and on the browser.

For example:

async function getResult() {
  const result = await Promise.resolve(100);
  console.log(result);
}

getResult();

As you can see, we have wrapped the await keyword into an async function called getResult. We then call this function to log the result to the console.

Output:

100

Frequently Askes Questions (FAQs)

What happens if I mistakenly use await keyword outside of an async function?

When you mistakenly use await outside of an async function, you will encounter a syntaxerror: await is only valid in async function error.

This error serves as a reminder to ensure that the await keyword is used within the appropriate context, which is an async function.

Can I use the await keyword in a callback function?

Definitely, no, you cannot directly use the await keyword in a callback function. However, you can wrap the callback function inside an async function and use await within that function to handle asynchronous operations.

Conclusion

In conclusion, the error message syntaxerror await is only valid in async function occurs when you are trying to use the await keyword outside of an asynchronous function.

This error message is easy to fix, you can wrap the await keyword into an async function. The await keyword can only be used inside an async function.

This article already discussed what this error is all about and multiple ways to resolve this error.

By executing the solutions above, you can master this SyntaxError with the help of this guide.

You could also check out other SyntaxError articles that may help you in the future if you encounter them.

We are hoping that this article helps you fix the error. Thank you for reading itsourcecoders 😊

Leave a Comment