Acces to jQuery $.get URL from Bluebird Promise object

476 views Asked by At

I use Bluebird promises with jQuery $.get() like so:

var p = Promise.resolve($.get(url.address, url.options, 'json')).then(function (result) {...

and handle them with:

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
});

How to have acces in above catch block to $.get URL with options? See comment in code - I need to know what user asked for in his request when I catch timeout.

Example provided is simplified and I pass Promise to another function and in there accessing it; what am I getting there is:

Promise {
    _bitField: 201326593,
    _cancellationParent: undefined,
    _fulfillmentHandler0: undefined,
    _progressHandler0: undefined,
    _promise0: undefined,
    _receiver0: undefined,
    _rejectionHandler0: undefined,
    _settledValue: SubError,
    __proto__: Promise
}

I am not asking how to get $.get() url in essence but how to get it in scope of Bluebird promise.

1

There are 1 answers

1
taminov On BEST ANSWER

You shouldn't access the promise object directly, let the framework handle it. If you want to pass parameters, you can return a parameter value in a promise (but it will only stick in the next then) or you can use promise's scope: 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);
});