javascript - 从 Bluebird Promise 对象访问 jQuery $.get URL

标签 javascript jquery promise bluebird

我将 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/

相关文章:

javascript - 强制对每个复选框/下拉列表更改进行 POST

javascript - 使用 javascript 验证 html 表单

php - Jquery 在 php echo 中显示隐藏的 Div

javascript - 鼠标悬停鼠标离开 - 子菜单

javascript - 设置边界等于overlayImage谷歌地图

javascript - Jquery AJAX promise 在 ajax 失败时总是中断

javascript - 为什么 React.js 在使用标记库时不加载 HTML 代码

JavaScript 随机报价生成器

swift - Swift 和 Spring 中的链接动画无法正常工作

javascript - 原生 JS Promise 重试包装器