rdb*_*max 2 javascript class chaining node.js ecmascript-6
我想从类中链接方法.我有同步方法的问题,但我不知道如何使用异步方法.
例如,这个类:
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
}
}
Run Code Online (Sandbox Code Playgroud)
这有效:
new Example().sync().check()
> 1
Run Code Online (Sandbox Code Playgroud)
但这不起作用:
new Example().async().check()
> TypeError: Cannot read property 'check' of undefined
Run Code Online (Sandbox Code Playgroud)
PS我想要链接,而不是地狱回调.
我希望你能check()在超时到期后打电话.问题是,分叉,你不能立即有东西可以返回.
你可以传入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)
Run Code Online (Sandbox Code Playgroud)
......或承诺
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())
Run Code Online (Sandbox Code Playgroud)
......或者你可以使用ES6发电机
如果您只想new Example().async().check()工作,则只需return this在调用setTimeout之后即可。例如:
async () {
setTimeout(() => {
this.val += 1
}, 5000)
return this
}
Run Code Online (Sandbox Code Playgroud)
的 return this超时内是没有必要的,因为它会在其自身上执行。那时,它基本上是独立运行的。
的确,如果您希望整个事情完全异步运行,并且能够控制某些事情何时发生的流程,则需要使用promise来实现。