我在类中编写了一系列 Promise:
class Executor {
someFunction(){
return Promise.resolve(function(){
console.log(this.name);
});
};
someOtherFunction(){
return Promise.resolve(function(){
console.log(this.date);
});
};
execute(){
let {someFunction, someOtherFunction} = this;
this.name = "John";
this.date = "Saturday";
someFunction=someFunction.bind(this)
someFunction().then(someOtherFunction.bind(this));
}
}
然后我通过实例化该类并运行 execute
方法来调用它:
var e = new Executor;
e.execute();
是否有更好的方法将类的上下文绑定(bind)到多个函数,而不是编写多个 bind()
语句?
最佳答案
你真的不需要在这里破坏,这只会让事情变得复杂,KISS :
'use strict';
class Executor {
someFunction() {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log(this.name);
resolve();
}, 250);
});
};
someOtherFunction() {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log(this.date);
resolve();
}, 250);
});
};
execute() {
this.name = "John";
this.date = "Saturday";
this.someFunction()
.then(() => this.someOtherFunction())
.then(() => { console.log('done!'); });
}
}
let e = new Executor();
e.execute();
请注意,您的 Promise
用法已被破坏。
关于javascript - 将相同的上下文绑定(bind)到多个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33561224/