Ephraim Atta-Duncan
Ephraim Atta-Duncan

Ephraim Atta-Duncan

Use 'await' without an 'async' function

Ephraim Atta-Duncan's photo
Ephraim Atta-Duncan
·Nov 27, 2020·

3 min read

Subscribe to my newsletter and never miss my upcoming articles

Play this article

async/await functions was released in ES7 as a wrapper for Promises and the await keyword was not used without a wrappingasync function. Using await without an async will give an error.

// SyntaxError: await is only valid in async function

There is a proposal to use await without an async function but Node.js 14.3.0 and Google Chrome has already implemented this feature.

We will see how you can use an await without a wrapping async function in Node.js.

First, you'll need to update your node version if your version is below 14.3.0. You can use nvm to update or get the latest version at the official downloads page.

# Using `nvm`
nvm install 14.3.0

Now that we have Node updated, we can use await on it's own. Create a new directory and run

npm init -y

Then in the generated package.json file, add "type": "module". We will be using ES Modules. Create a new file in the same directory as your package.json, index.js. We are done with the setup. In your terminal, install axios using npm.

# Installing `axios`
npm install axios

When the installation is done, you can head over to your index.js file and write some code. We are going to make a simple GET request to an API endpoint and log the response to the terminal but we will be using await without an async wrapper function.

// Because we are using ES Modules
import axios from 'axios';

// Making `GET` request with `axios`
const response = await axios.get("https://rickandmortyapi.com/api/character/");

// Log the data 
console.log(response.data);

We can run the file and see the results.

// Any of the commands below will work.
node --harmony-top-level-await index.js 
node index.js  // Works without the flag now

// {
//   info: {
//     count: 671,
//     pages: 34,
//     next: 'https://rickandmortyapi.com/api/character/?page=2',
//     prev: null,
//   },
//   results: [
//     // ...
//   ],
// };

That's how you can use await without an async. For more information, check out this blog.

 
Share this