Gly*_*ird 70 javascript asynchronous node.js
我正在尝试await
Node.js中的关键字.我有这个测试脚本:
"use strict";
function x() {
return new Promise(function(resolve, reject) {
setTimeout(function() {
resolve({a:42});
},100);
});
}
await x();
Run Code Online (Sandbox Code Playgroud)
但是当我在节点中运行它时,我得到了
await x();
^
SyntaxError: Unexpected identifier
Run Code Online (Sandbox Code Playgroud)
无论是使用Node.js 7.5还是Node.js 8(每晚构建)在我的Mac上使用node
或运行node --harmony-async-await
Node.js'repl'.
奇怪的是,相同的代码在Runkit JavaScript笔记本环境中工作:https://runkit.com/glynnbird/58a2eb23aad2bb0014ea614b
我究竟做错了什么?
Gly*_*ird 103
感谢其他评论者和其他一些研究await
只能用于一个async
功能,例如
async function x() {
var obj = await new Promise(function(resolve, reject) {
setTimeout(function() {
resolve({a:42});
},100);
});
return obj;
}
Run Code Online (Sandbox Code Playgroud)
然后我可以将此函数用作Promise,例如
x().then(console.log)
Run Code Online (Sandbox Code Playgroud)
或者在另一个异步函数中.
令人困惑的是,Node.js repl不允许你这样做
await x();
Run Code Online (Sandbox Code Playgroud)
RunKit笔记本环境的位置.
Cod*_*y G 34
正如其他人所说,你不能在异步函数之外调用'await'.但是,为了解决这个问题,你可以包装await x(); 在异步函数调用中.也就是说,
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)
}
})();
Run Code Online (Sandbox Code Playgroud)
这应该在Node 7.5或更高版本中有效.也适用于镀铬金丝雀片段区域.
小智 16
所以其他人建议await将在异步内部工作.所以你可以使用下面的代码来避免使用:
async function callX() {
let x_value = await x();
console.log(x_value);
}
callX();
Run Code Online (Sandbox Code Playgroud)