【发布时间】:2017-09-13 02:12:57
【问题描述】:
节点 7.9.0
这是场景:
class TestClass {
constructor() {
const x = await this.asyncFunc()
console.log(x)
}
async asyncFunc() {
return new Promise((accept) => {
setTimeout(() => accept("done"), 1000)
})
}
}
new TestClass()
第3行的错误是Unexpected token this
好的,所以我就这样结束了...const x = await (this.asyncFunc())
现在我得到await is not defined
这让我觉得节点 7.9.0 不知道等待/同步,尽管 http://node.green/ 告诉我它受支持并且它的示例运行得很好。
(function(){
(async function (){
await Promise.resolve();
var a1 = await new Promise(function(resolve) { setTimeout(resolve,800,"foo"); });
var a2 = await new Promise(function(resolve) { setTimeout(resolve,800,"bar"); });
if (a1 + a2 === "foobar") {
console.log("passed")
}
}());
})()
【问题讨论】:
-
请注意,在示例中,
await在async函数中使用。你的代码在这方面是不同的。 -
...所以你需要一个异步构造函数...
-
你不能在构造函数中使用
await。但是,您可以使用this.asyncFunc().then(console.log)。但是,通常应避免在构造函数中进行异步处理。 -
您可能想签出this。
标签: javascript node.js asynchronous async-await