简体   繁体   English

在没有 async 关键字的全局范围内使用 await

[英]using await on global scope without async keyword

I am trying to do something like this on global scope in nodejs REPL.我正在尝试在 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我的节点版本是 v8.9.4

Update更新

When using Node , the file currently must have an .mjs extension to work.使用Node时,该文件当前必须具有.mjs扩展名才能工作。

Top level awaits can be used in browser modules.顶级awaits可以在浏览器模块中使用。 When used the script tag must include the type attribute which must be set to module :使用时,脚本标签必须包含type属性,该属性必须设置为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))
}

Old Answer旧答案

await can only be used within a function that is labeled async , so there are two ways you can approach this. await只能在标记为async的函数中使用,因此有两种方法可以解决这个问题。

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()或者第二种方法是使用.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.该提案目前处于 TC39 流程的第 3 阶段。 LINK关联

You can use this feature in Google Chrome and Mozilla Firefox as of now.您现在可以在 Google Chrome 和 Mozilla Firefox 中使用此功能。 You can use top level await without async in console.您可以在控制台中使用没有异步的顶级等待。

控制台中的顶级等待

https://twitter.com/addyosmani/status/1080365576218759168 https://twitter.com/addyosmani/status/1080365576218759168

As of version 13.3, Node.js support Top-level await .从 13.3 版本开始,Node.js 支持顶级 await

Top-level await means you can now use await operator outside an async function.顶级await意味着您现在可以在async函数之外使用await运算符。 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.注意:顶级 await 仅适用于顶级模块。 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 .请记住await运算符用于等待Promise It does NOT matter if you are using an await operator with a value other than a Promise.如果您使用的await运算符的值不是 Promise,则无关紧要。 For example, the name variable in the displayName()` function:例如 displayName()` 函数中的name变量:

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.由于name变量的值不是 Promise,因此它将值转换为已解析的 Promise,并等待它。 It happens under the hood.它发生在引擎盖下。

The old behavior老行为

MDN doc says MDN 文档

The await operator is used to wait for a Promise. await 运算符用于等待 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);
})();

Source: https://javascript.plainenglish.io/5-javascript-interview-questions-to-identify-outstanding-developers-859a71c3d7f资料来源: https ://javascript.plainenglish.io/5-javascript-interview-questions-to-identify-outstanding-developers-859a71c3d7f

Top-level-await is supported in Node.js version 13.3 or above Node.js 13.3 及以上版本支持顶级等待

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 ) (虽然问题是关于 REPL,关于作为脚本文件运行的说明。设置{"type": "module"} package.json或使用文件扩展名.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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM