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
When using Node , the file currently must have an .mjs
extension to work.
Top level awaits
can be used in browser modules. When used the script tag must include the type
attribute which must be set to module
:
<script src="/script.js" type="module"></script>
const start = Date.now()
console.log('Pre call.')
await delayedCall()
console.log('Duration:', Date.now() - start)
function delayedCall() {
return new Promise(resolve => setTimeout(() => resolve(), 2000))
}
node ./index.mjs
in the terminal.await
can only be used within a function that is labeled async
, 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:
(async function() { let x = await Promise.resolve(2) let y = await 2 console.log(x, y) })()
Or the second way is to use .then()
Promise.resolve(2).then(async data => { let x = data let y = await 2 console.log(x, y) })
This proposal is currently in stage 3 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.
As of version 13.3, Node.js support Top-level await .
Top-level await
means you can now use await
operator outside an async
function. So both examples are correct:
(async function() {
await Promise.resolve(console.log('Hello await!'));
}());
// or
await Promise.resolve(console.log('Hello await!'));
Note : Top-level await only works at the top level of modules. There is no support for classic scripts or non-async functions.
Just keep in mind , that the await
operator is used to wait for a Promise . It does NOT matter if you are using an await
operator with a value other than a Promise. For example, the name
variable in the displayName()` function:
async function displayName() {
const name = await 'unclexo';
console.log(name);
}
displayName(); // outputs 'unclexo'
As the value of the name
variable is not a Promise, it converts the value to a resolved Promise, and waits for it. It happens under the hood.
The old behavior
MDN doc says
The await operator is used to wait for a Promise. It can only be used inside an async function.
从节点 10 开始,您可以使用 --experimental-repl-await 运行节点进程以允许顶级等待https://nodejs.org/api/repl.html#repl_await_keyword
async function getTen() {
return 10;
}
(async () => {
let ten = await getTen();
console.log(ten);
})();
Top-level-await is supported in Node.js version 13.3 or above
Example:
await Promise.resolve(console.log('🎉')); // → 🎉
(Though the question is about REPL, a note on running as script file. Set {"type": "module"}
package.json or use the file name extension .mjs )
You could wrap all the code in the global scope in an async function.
For example:
// ...global imports...
new Promise (async () => {
// ...all code in the global scope...
}).then()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.