我遇到了需要将一些值传递给Promise处理程序的情况。以下是情况示例
function promiseFunct(x){
return new Promise(function(resolve, reject){
if(x>0) resolve(x);
else if(x==0) resolve(1);
else resolve(0);
});
}
promiseFunct(-100).then(function(response){
var someObj = { len: 124 };
return promiseFunct(response).bind(someObj);
}).then(function(response){
if(this.len) console.log(this.len); //not getting access here, this is Window
});
我试图绑定someObj,然后在处理程序中访问它,但没有成功。除了传递给Promise然后在Promise内部解析外,是否有一些优雅的解决方案可以将某些对象传递给Promise处理程序?
找到了简单的解决方案,但不能保证它是最优雅的。
promiseFunct(-100).bind({}).then(function(response){
this.len = 124 ;
return promiseFunct(response);
}).then(function(response){
if(this.len) console.log(this.len); // showing 124
});
例如,使用bind({})
设置自己的Promise链上下文不会与Window
交叉。如果我的len
值不在外面,则可以使用bind({len: len})
然后,我可以使用this.propertyName
获取或设置要在下一个处理程序中使用的所需属性。
首先看一下出了什么问题:
promiseFunct(-100).then(function(response){
var someObj = { len: 124 };
return promiseFunct(response).bind(someObj);
})
从then
履行处理程序返回绑定的承诺。
承诺代码要等到绑定的承诺被解决后,再将其状态(已实现或拒绝)和值(数据或拒绝原因)向下传递到承诺链。为此,它内部在绑定的promise上调用then
以获取其结果,这是所使用的内部处理程序以绑定的this
值被调用-他们只是忽略了。]
...另外,从绑定承诺派生的承诺也将是具有相同thisArg ...]的绑定承诺。
不适用于这种情况:承诺链中的所有承诺都是在定义该链时,在该链的任何异步处理开始之前同步创建的。
由于诺言链仅在处理程序之间传递单个值,所以最简单的方法可能是根据需要传递带有任意数量其他值的名称空间对象。由于后续处理程序已经需要知道在哪里查找其他数据,因此更改不会太大:
function promiseFunct(x){
return new Promise(function(resolve, reject){
if(x>0) resolve(x);
else if(x==0) resolve(1);
else resolve(0);
});
}
promiseFunct(-100).then(function(response){
console.log( "response " + response);
var someObj = { len: 124 };
var ns = {response, rest: someObj};
return ns;
}).then(function({response, rest}){
if(rest.len) console.log(rest.len);
console.log(response);
});