我正在 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 许可协议
感谢其他评论者和其他一些研究
await
只能用于async
函数,例如然后我可以将此功能用作 Promise 例如
或者在另一个异步函数中。
令人困惑的是,Node.js repl 不允许你这样做
与 RunKit notebook 环境一样。