我有一些代码,例如:
var bar = foo().then(function success(value) {
// compute something from a value...
}, function failure(reason) {
// handle an error...
});
如何将failure
函数绑定this
到bar
. 我知道我将不得不使用myFunc.bind(this)
,但我可以用什么代替myFunc
?
我有一些代码,例如:
var bar = foo().then(function success(value) {
// compute something from a value...
}, function failure(reason) {
// handle an error...
});
如何将failure
函数绑定this
到bar
. 我知道我将不得不使用myFunc.bind(this)
,但我可以用什么代替myFunc
?
你可以bind
这样使用:
var bar = foo().then(function success(value) {
// compute something from a value...
}, function failure(reason) {
// handle an error...
}.bind(this));
您当前有一个用于失败回调的匿名(尽管已标记)函数:
function failure(reason) {
// handle an error...
}
正如 robertklep 所说,您可以立即调用.bind
该匿名函数。但是,使用命名函数可能更易读,并将其.then()
作为变量传递:
function success(value) {
// compute something from a value...
}
function failure(reason) {
// handle an error...
}
var bar = foo().then(success, failure.bind(this));
如果您只对this
封闭范围的对象感兴趣,并且您使用的是 ECMA6 或更高版本,则可以使用箭头函数。它看起来像:
var that = this;
var bar = foo().then(value => {
// compute something from a value...
console.log(this === that); // true
this.propA = value.propA
});
您可以在MSD Using promises中找到更多示例
我发现非常有用的是将 eachthen()
的 [function] 处理程序绑定到一个空对象,这样每个函数都可以访问它。然后用户可以通过关键字设置和获取每个 Promise 中的属性this
。单元测试框架的工作方式类似。
chainPromiseList([getName,getAge],finalDone,rejectHandle);
function chainPromiseList(promiseList,finalDone,errHandle){
var userContext = new UserContext();
if(typeof finalDone==='function') promiseList.push(finalDone);
if(typeof errHandle==='function') promiseList.push(errHandle);
return promiseList.reduce((total,curVal,curInd,arr)=>{
var last = curInd+1===arr.length;
var method = last&&typeof errHandle==='function' ? 'catch':'then';
var concatenated = total[method](curVal.bind(userContext));
return concatenated;
},Promise.resolve());
function UserContext(){};
}
function getName(){
return new Promise((resolve,reject)=>{
setTimeout(()=>{
console.log('got name!');
this.name = 'Paul';
resolve();
},500);
});
}
function getAge(){
return new Promise((resolve,reject)=>{
setTimeout(()=>{
console.log('got age!');
this.age = 26;
resolve();
},500);
});
}
function finalDone(){
console.log(`Hello, I'm ${this.name} and I'm ${this.age}yo.`);
}
function rejectHandle(msg){
console.log('Error: ',msg);
}