如何在JavaScript ES6类中链接异步方法 [英] How to chain async methods in javascript ES6 classes
本文介绍了如何在JavaScript ES6类中链接异步方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想链接一个类的方法。我有同步方法的问题,但我不知道如何使用异步方法。
I want to chain methods from a class. I have o problems with synchronous methods, but I don't know how to do it with asynchronous methods.
例如,这个类:
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
P.S。我想要链接,而不是地狱回调。
P.S. I want chaining, not Hell Callbacks.
推荐答案
我希望你想要调用 check() / code>超时后过期。问题是,叉子不能立即有东西可以返回。
I expect that you want to call check()
after the timeout has expired. The problem is that forks off, and you can't immediately have something available to return.
你可以传入 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)
...或承诺
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生成器
... Or you could use ES6 generators
这篇关于如何在JavaScript ES6类中链接异步方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文