I am trying to do something like this on global scope in nodejs REPL. As per my understanding both the following statements are valid. see docs
let x = await Promise.resolve(2);
let y = await 2;
However, both these statements are throwing an error.
Can somebody explain why? my node version is v8.9.4
This proposal is currently in stage 2 of the TC39 process. LINK
You can use this feature in Google Chrome and Mozilla Firefox as of now. You can use top level await without async in console.
https://twitter.com/addyosmani/status/1080365576218759168
await
can only be used within a function that is labeledasync
, so there are two ways you can approach this.Note: There is a proposal in place that may eventually allow the usage of Top level await calls.
The first way is to create a self invoked function like this:
Or the second way is to use
.then()
You can not do that. MDN doc says
since node 10, you can run node process with --experimental-repl-await to allow to level await https://nodejs.org/api/repl.html#repl_await_keyword
You could wrap all the code in the global scope in an async function.
For example: