Node.js 7.5 上的“等待意外标识符”

新手上路,请多包涵

我正在 Node.js 中试验 await 关键字。我有这个测试脚本:

 "use strict";
function x() {
  return new Promise(function(resolve, reject) {
    setTimeout(function() {
      resolve({a:42});
    },100);
  });
}
await x();

但是当我在节点中运行它时,我得到

await x();
      ^
SyntaxError: Unexpected identifier

无论我是使用 node 还是 node --harmony-async-await 运行它,还是在我的 Mac 上使用 Node.js 7.5 或 Node.js 8(每晚构建)运行它。

奇怪的是,相同的代码在 Runkit JavaScript 笔记本环境中工作: https ://runkit.com/glynnbird/58a2eb23aad2bb0014ea614b

我究竟做错了什么?

原文由 Glynn Bird 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 416
2 个回答

感谢其他评论者和其他一些研究 await 只能用于 async 函数,例如

async function x() {
  var obj = await new Promise(function(resolve, reject) {
    setTimeout(function() {
      resolve({a:42});
    },100);
  });
  return obj;
}

然后我可以将此功能用作 Promise 例如

x().then(console.log)

或者在另一个异步函数中。

令人困惑的是,Node.js repl 不允许你这样做

await x();

与 RunKit notebook 环境一样。

原文由 Glynn Bird 发布,翻译遵循 CC BY-SA 3.0 许可协议

正如其他人所说,您不能在异步函数之外调用“等待”。但是,要解决此问题,您可以包装 await x();在异步函数调用中。 IE,

 function x() {
  return new Promise(function(resolve, reject) {
    setTimeout(function() {
      resolve({a:42});
    },100);
  });
}
//Shorter Version of x():
var x = () => new Promise((res,rej)=>setTimeout(() => res({a:42}),100));

(async ()=>{
    try{
      var result = await x();
      console.log(result);
    }catch(e){
      console.log(e)
    }
})();

这应该适用于 Node 7.5 或更高版本。也适用于 chrome canary 片段区域。

原文由 Cody G 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏