繁体   English   中英

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

[英]using await on global scope without async keyword

我正在尝试在 nodejs REPL 的全局范围内做这样的事情。 根据我的理解,以下两个陈述都是有效的。 见文档

let x = await Promise.resolve(2);
let y = await 2;

但是,这两个语句都引发了错误。

有人可以解释为什么吗? 我的节点版本是 v8.9.4

更新

使用Node时,该文件当前必须具有.mjs扩展名才能工作。

顶级awaits可以在浏览器模块中使用。 使用时,脚本标签必须包含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))
}

旧答案

await只能在标记为async的函数中使用,因此有两种方法可以解决这个问题。

注意:有一个提案可能最终允许使用顶级等待调用。

第一种方法是创建一个像这样的自调用函数:

 (async function() { let x = await Promise.resolve(2) let y = await 2 console.log(x, y) })()

或者第二种方法是使用.then()

 Promise.resolve(2).then(async data => { let x = data let y = await 2 console.log(x, y) })

该提案目前处于 TC39 流程的第 3 阶段。 关联

您现在可以在 Google Chrome 和 Mozilla Firefox 中使用此功能。 您可以在控制台中使用没有异步的顶级等待。

控制台中的顶级等待

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

从 13.3 版本开始,Node.js 支持顶级 await

顶级await意味着您现在可以在async函数之外使用await运算符。 所以这两个例子都是正确的:

(async function() {

  await Promise.resolve(console.log('Hello await!'));

}());

// or

await Promise.resolve(console.log('Hello await!'));

注意:顶级 await 仅适用于顶级模块。 不支持经典脚本或非异步函数。

请记住await运算符用于等待Promise 如果您使用的await运算符的值不是 Promise,则无关紧要。 例如 displayName()` 函数中的name变量:

async function displayName() {

  const name = await 'unclexo';

  console.log(name);
}

displayName(); // outputs 'unclexo'

由于name变量的值不是 Promise,因此它将值转换为已解析的 Promise,并等待它。 它发生在引擎盖下。

老行为

MDN 文档

await 运算符用于等待 Promise。 它只能在异步函数中使用。

从节点 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);
})();

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

Node.js 13.3 及以上版本支持顶级等待

例子:

await Promise.resolve(console.log('🎉')); // → 🎉

(虽然问题是关于 REPL,关于作为脚本文件运行的说明。设置{"type": "module"} package.json或使用文件扩展名.mjs

您可以将全局范围内的所有代码包装在异步函数中。

例如:

// ...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