[英]Problem with passing context in Bluebird Promise chain
我遇到了需要将一些值传递给 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 代码等待绑定的 Promise 被解决,然后将其状态(已完成或已拒绝)和值(数据或拒绝原因)向下传递到 Promise 链。 要做到这一点,在内部调用then
在绑定的承诺,以获得其结果,它是使用的内部处理程序,其被调用与约束this
值-他们根本不理。
尽管Bluebird 文档指出
...此外,从绑定承诺派生的承诺也将是具有相同 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); });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.