await outside async function in node -v 14.3

Viewed 448

I read in the blog of version 14.3 release that the version has the support for Top-Level Await. Is that mean that this code must work and if not what is the meaning of [support for Top-Level Await]

let x = 0

let myFunc = () => {
    setTimeout(() => {
    x = 2
    }, 1000)
  return x
  }

let y = await myFunc()

console.log(y)

Cuz it didn't work in my updated node environment

2 Answers

Yes it is true that Node.js now has support for top-level await, although the language has not fully implemented it yet stage 3. You can run your Node.js script with the --harmony-top-level-await flag

node --harmony-top-level-await ./beer.js
async function beer(){
    return ""
}

const result = await test();
console.log(result); // ""

You may stil be getting this following error;

SyntaxError: await is only valid in an async function

To tackle this you need to tell node that your script is of type module. You can achieve this 2 ways;

Set package.json type to module

{
  "main": "beer.js",
  "type": "module"
}
node --harmony-top-level-await ./beer.js

Or Change to a .mjs extension ./beer.js => ./beer.mjs

node --harmony-top-level-await ./beer.mjs

Yes, as @DanStarns told in his answer,

I tried to implement this example,

import axios from 'axios';

const response = await axios('https://quote-garden.herokuapp.com/api/v2/quotes/random');
console.log(response.data);

package.json

{
  "name": "async-await-top",
  "version": "1.0.0",
  "description": "",
  "main": "top-level-async-await.js",
  "type": "module",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "axios": "^0.19.2"
  }
}

Run with flag

node --harmony-top-level-await top-level-async-await.js

Output

G:\async-await-top>node --harmony-top-level-await top-level-async-await.js
{
  statusCode: 200,
  quote: {
    _id: '5eb17aaeb69dc744b4e72b82',
    quoteText: 'I can take more punishment than anyone in the business.',
    quoteAuthor: 'Ric Flair',
    quoteGenre: 'business',
    __v: 0
  }
}
Related