问题描述
我正在尝试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
我是否用<$ c运行它$ c> node 或 node --harmony-async-await
或在带有Node.js 7.5的Mac上的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笔记本环境中有效:
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;
}
然后我可以将此函数用作承诺,例如
I could then use this function as a Promise e.g.
x().then(console.log)
或另一个异步函数。
令人困惑的是,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上“等待意外的标识符”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!