Node.js 7.5 上的“等待意外标识符" [英] 'await Unexpected identifier' on Node.js 7.5
问题描述
我正在 Node.js 中试验 await
关键字.我有这个测试脚本:
I am experimenting with the await
keyword in Node.js. I have this test script:
"use strict";
function x() {
return new Promise(function(resolve, reject) {
setTimeout(function() {
resolve({a:42});
},100);
});
}
await x();
但是当我在节点中运行它时,我得到
But when I run it in node I get
await x();
^
SyntaxError: Unexpected identifier
我是否使用 node
或 node --harmony-async-await
或在我的 Mac 上使用 Node.js 7.5 的 Node.js 'repl' 运行它,或者Node.js 8(每晚构建).
whether I run it with node
or node --harmony-async-await
or in the Node.js 'repl' on my Mac with Node.js 7.5 or Node.js 8 (nightly build).
奇怪的是,同样的代码在 Runkit JavaScript notebook 环境中也有效:https://runkit.com/glynnbird/58a2eb23aad2bb0014ea614b
Oddly, the same code works in the Runkit JavaScript notebook environment: https://runkit.com/glynnbird/58a2eb23aad2bb0014ea614b
我做错了什么?
推荐答案
感谢其他评论者和其他一些研究 await
只能在 async
函数中使用,例如
Thanks to the other commenters and some other research await
can only be used in an async
function e.g.
async function x() {
var obj = await new Promise(function(resolve, reject) {
setTimeout(function() {
resolve({a:42});
},100);
});
return obj;
}
然后我可以将此函数用作 Promise,例如
I could then use this function as a Promise e.g.
x().then(console.log)
或在另一个异步函数中.
or in another async function.
令人困惑的是,Node.js repl 不允许您这样做
Confusingly, the Node.js repl doesn't allow you to do
await x();
RunKit 笔记本环境的作用.
where as the RunKit notebook environment does.
这篇关于Node.js 7.5 上的“等待意外标识符"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!