Javascript - 将 this 参数绑定到 Promise
Javascript - Bind a this parameter to Promise
我需要一个应用程序将此参数绑定到 Promise,但我找不到如何执行此操作...
这正是我想要做的:
var myPromise = new Promise((resolve, reject) => {
console.log(this);
});
myPromise.then();
我希望"this"拥有我想要的价值。因为我需要在外面定义它。
可能吗?
注意:我想避免这个解决方案:
var myPromise = (that) => {
return new Promise((resolve, reject) => {
console.log(that);
})
}
myPromise().then();
因为它使代码变得非常沉重。
箭头函数具有词法 "this" 绑定,thus it gets "this" from the enclosing context.
如果您希望由 指定绑定,您应该尝试使用 bind。示例代码:
new Promise(function(resolve, reject) {
console.log(this);
}.bind(that));
我需要一个应用程序将此参数绑定到 Promise,但我找不到如何执行此操作...
这正是我想要做的:
var myPromise = new Promise((resolve, reject) => {
console.log(this);
});
myPromise.then();
我希望"this"拥有我想要的价值。因为我需要在外面定义它。
可能吗?
注意:我想避免这个解决方案:
var myPromise = (that) => {
return new Promise((resolve, reject) => {
console.log(that);
})
}
myPromise().then();
因为它使代码变得非常沉重。
箭头函数具有词法 "this" 绑定,thus it gets "this" from the enclosing context.
如果您希望由 指定绑定,您应该尝试使用 bind。示例代码:
new Promise(function(resolve, reject) {
console.log(this);
}.bind(that));