Javascript Node.js 7.5 上的“等待意外标识符”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42225480/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
'await Unexpected identifier' on Node.js 7.5
提问by Glynn Bird
I am experimenting with the awaitkeyword in Node.js. I have this test script:
我正在尝试使用awaitNode.js 中的关键字。我有这个测试脚本:
"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
whether I run it with nodeor node --harmony-async-awaitor in the Node.js 'repl' on my Mac with Node.js 7.5 or Node.js 8 (nightly build).
我是否符合运行node或node --harmony-async-await或Node.js的在我的Mac“REPL”用Node.js的7.5或Node.js的8(每日构建)。
Oddly, the same code works in the Runkit JavaScript notebook environment: https://runkit.com/glynnbird/58a2eb23aad2bb0014ea614b
奇怪的是,同样的代码在 Runkit JavaScript notebook 环境中有效:https://runkit.com/glynnbird/58a2eb23aad2bb0014ea614b
What am I doing wrong?
我究竟做错了什么?
回答by Glynn Bird
Thanks to the other commenters and some other research awaitcan only be used in an asyncfunction e.g.
感谢其他评论者和其他一些研究await只能在async函数中使用,例如
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.
然后我可以使用这个函数作为一个 Promise 例如
x().then(console.log)
or in another async function.
或在另一个异步函数中。
Confusingly, the Node.js repl doesn't allow you to do
令人困惑的是,Node.js repl 不允许你这样做
await x();
where as the RunKit notebook environment does.
就像 RunKit 笔记本环境一样。
回答by Cody G
As others have said, you can't call 'await' outside of an async function. However, to get around this you can wrap the await x(); in an async function call. I.e.,
正如其他人所说,您不能在异步函数之外调用“await”。但是,要解决此问题,您可以包装 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)
}
})();
This should work in Node 7.5 or above. Also works in chrome canary snippets area.
这应该适用于 Node 7.5 或更高版本。也适用于 chrome canary 片段区域。
回答by user3013823
so as suggested by others await will work inside async. So you can use the below code to avoid using then:
所以正如其他人所建议的那样,await 将在异步内工作。所以你可以使用下面的代码来避免使用 then:
async function callX() {
let x_value = await x();
console.log(x_value);
}
callX();

