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.)