---
title: "Top Level Await Node REPL"
description: "Using await keyword outside of async functions in Node.js REPL. Practical notes and code examples on Top Level Await Node."
url: "https://h3manth.com/scribe/top-level-await-node-repl/"
canonical_url: "https://h3manth.com/scribe/top-level-await-node-repl/"
markdown_url: "https://h3manth.com/scribe/blog/top-level-await-node-repl.md"
publishDate: "2020-05-23T00:00:00.000Z"
author: "Hemanth HM"
category: "node"
tags: ["node","javascript","async","await"]
word_count: 222
reading_time_minutes: 2
x_markdown_tokens: 470
content_signal: "ai-train=yes, search=yes, ai-input=yes"
---

# Top Level Await Node REPL

> Using await keyword outside of async functions in Node.js REPL. Practical notes and code examples on Top Level Await Node.

One can use the `await` keyword outside of `async` functions with [Top-level await](https://tc39.es/proposal-top-level-await/) and the happy news is you can use it today in Node and REPL.

As of today, if we execute the below piece of code in node env:

await Promise.resolve(42);

We would see a: `SyntaxError: await is only valid in async function`

So, we would normally mitigate this by wrapping it in an async function:

```javascript
(async function() {
  const answer = await Promise.resolve(42);
  // answer would be 42
}());
```

But with top level await it gets easier - we could just do `const answer = await Promise.resolve(42);` Note that this will only work at the top level of modules only.

## Node.js v14.3.0+ Support

Node.js [v14.3.0](https://nodejs.org/en/blog/release/v14.3.0/) was released with the support of top-level await! But we always had a flag to enable top-level await on the REPL, ever since node v10!

The `--experimental-repl-await` enables experimental top-level await keyword support in REPL, so all you have to do is start the REPL with the flag `node --experimental-repl-await` and that's it.

## Usage in Scripts

```javascript
// home.mjs
export function home() {
  return 'Hello home!';
}
```

```javascript
// index.mjs
const home = await import('./home.mjs');
console.log(home());
```

You could execute this using `node --experimental-top-level-await`.

**TL;DR**: For REPL we would need `--experimental-repl-await` and for `.mjs` scripts `--experimental-top-level-await` as of today.
