我想链接类中的方法。我对同步方法有 o 问题,但我不知道如何使用异步方法。
例如这个类:
class Example {
constructor() {
this.val = 0
}
async () {
setTimeout(() => {
this.val += 1
return this
}, 5000)
}
sync () {
this.val += 1
return this
}
check () {
console.log('checker', this.val)
return this
}
}
这个有效:
new Example().sync().check()
> 1
但这行不通:
new Example().async().check()
> TypeError: Cannot read property 'check' of undefined
附言我想要链接,而不是 hell 回调。
最佳答案
我希望您在超时到期后调用 check()
。问题是 fork ,您无法立即返回可用的东西。
你可以传入 check()
作为回调:
class Example {
constructor() {
this.val = 0
}
async (callback) {
setTimeout(() => {
this.val += 1
callback()
}, 5000)
}
sync () {
this.val += 1
return this
}
check () {
console.log('checker', this.val)
return this
}
}
// execution
var ex = new Example();
ex.async(ex.check)
……或者一个 promise
class Example {
constructor() {
this.val = 0
}
async (callback) {
var deferred = Q.defer()
setTimeout(() => {
this.val += 1
deferred.resolve();
}, 5000)
return deferred.promise;
}
sync () {
this.val += 1
return this
}
check () {
console.log('checker', this.val)
return this
}
}
// execution
var ex = new Example()
ex.async().then(() => ex.check())
...或者你可以使用 ES6 生成器
关于javascript - 如何在 JavaScript ES6 类中链接异步方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32655656/