1

I am still new to Promise (as in Promises/A+, not jQuery), and would like to convert some of my older client-side code into returning Promise so that downstream can be thenable instead having to pass the callback to upstream, in particular, anything to do with web storage and AJAX.

Problem is, the AJAX library (Oboe) I am using, it has a jQuery-style API but no .then method, which means I need to construct and return new Promise myself, but is following approach optimal? Can we do something using static Promise.resolve and Promise.reject without wrapping a function? My example follows:

old code

function makeRequest(uri, callback) {

    var request = ajax(uri);

    request.fail(function(err) {
        // handle failure
    });

    request.done(function(res) {
        callback(res);
    });

}

new code

function makeRequest(uri) {

    return new Promise(function(resolve, reject) {

        var request = ajax(uri);

        request.fail(function(err) {
            reject(err);
        });

        request.done(function(res) {
            resolve(res);
        });

    });

}

better code?

function makeRequest(uri) {

    var request = ajax(uri);

    request.fail(function(err) {
        // handle failure
    });

    request.done(function(res) {
        // handle complete
    });

    // this won't work without third-party .then support
    return Promise.resolve(request);

}

(I intend to do this using native Promise and polyfill alone, but if there is library that has a helper for this, I am glad to take a look at their implementation.)

bitinn
  • 9,188
  • 10
  • 38
  • 64
  • I haven't tried this before, but I think some promise libraries support jquery defers by simply wrapping around them, i.e. `new Promise(deferred)`, or some other syntax, have you tried this? – simonzack Sep 13 '14 at 04:18
  • I am not using jQuery, so no `.then` on `request`, I don't think Promise.resolve is that magical, it probably treat it like a normal fulfill without waiting for callback to fire. – bitinn Sep 13 '14 at 04:22
  • Why are you trying to wrap your Ajax function rather than just fixing it to return a real promise object so it has full-fledged promise support? – jfriend00 Sep 13 '14 at 04:37
  • 1
    It's not a 100-line library, and it does unusual stuff: [oboejs](http://oboejs.com/). I prefer not to mess with it (since it's not mine) – bitinn Sep 13 '14 at 04:39
  • You _have_ to use `new Promise` - if all the methods take the same kind of callback - you can extract that logic in a function. Closing as dupe of the canonical promisification question. – Benjamin Gruenbaum Sep 13 '14 at 06:53

0 Answers0