我将 Bluebird Promise 与 jQuery $.get()
结合使用,如下所示:
var p = Promise.resolve($.get(url.address, url.options, 'json')).then(function (result) {...
并处理它们:
p.timeout(100).catch(Promise.TimeoutError, function (error) {
console.log(p); // here I want to log in that Promise took too long to execute and access what user actually asked for
});
如何在上面的 catch block 中使用选项访问 $.get URL?请参阅代码中的注释 - 当我遇到超时时,我需要知道用户在他的请求中要求什么。
提供的示例经过简化,我将 Promise 传递给另一个函数并在那里访问它;我在那里得到的是:
Promise {
_bitField: 201326593,
_cancellationParent: undefined,
_fulfillmentHandler0: undefined,
_progressHandler0: undefined,
_promise0: undefined,
_receiver0: undefined,
_rejectionHandler0: undefined,
_settledValue: SubError,
__proto__: Promise
}
本质上我并不是在问如何获取 $.get()
url,而是如何在 Bluebird promise 的范围内获取它。
最佳答案
您不应该直接访问 Promise 对象,让框架处理它。如果你想传递参数,你可以在 Promise 中返回一个参数值(但它只会保留在下一个 then 中)或者你可以使用 Promise 的作用域: https://github.com/petkaantonov/bluebird/blob/master/API.md#binddynamic-thisarg---promise
var result = Promise.bind({url: url})
.then(function(){
return Promise.resolve($.get(url.address, url.options, 'json'));
}
.then(function() {
// access your url in then
console.log('then: ', this.url);
return Promise.reject();
})
.catch(function(err) {
// access your url in catch
console.log('catch: ', this.url);
});
关于javascript - 从 Bluebird Promise 对象访问 jQuery $.get URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30711686/