My main concern is , i need to explicitly resolve or reject according to the responses.
Good concern: No, you don't. Just use the results you're given by the promise from jQuery's post
.
Since you're using jQuery v1.x, I'll just note that its Deferred
object is not Promises/A+ compliant. You may or may not care about that. I'll assume you're using v1.8 or later, though.
So if you're okay with using jQuery's non-Promises/A+-compliant Deferred and promise, then just return the result of post
.
I'll stick with ES5 syntax, since you're using jQuery v1.x and I'm guessing you're not transpiling, etc.
function async1(my_id/* I assume it's a parameter?*/) {
return $j.post(
'/call1',
JSON.stringify({id: my_id})
);
}
function async2(my_id/* I assume it's a parameter?*/) {
return $j.post(
'/call2',
JSON.stringify({id: my_id})
);
}
...and in main
, use those "promises":
function main(some_id) {
return async1(some_id).then(function(result1) {
return async2(some_id).then(function(result2) {
return [result1, result2];
});
});
}
That example has main
returning a promise of an array, where the first entry in the array will be the result from async1
and the second is the result from async2
(or where it rejects because one of them failed). You can tweak that as you like, though, by changing the return in the second then
handler.
If you want main
to return a native promise instead (using a polyfill if necessary), I'd probably convert to native promises early by giving myself a wrapper for post
that provides a native promise:
function postPromise() {
var args = Array.prototype.slice.call(arguments);
return new Promise(function(resolve, reject) {
$j.post.apply($j, args)
.done(resolve)
.fail(function(jqXHR, textStatus, errorThrown) {
if (errorThrown) {
reject(errorThrown);
} else {
reject(new Error(textStatus)); // or whatever
}
});
});
}
then
function async1(my_id/* I assume it's a parameter?*/) {
return postPromise(
'/call1',
JSON.stringify({id: my_id})
);
}
function async2(my_id/* I assume it's a parameter?*/) {
return postPromise(
'/call2',
JSON.stringify({id: my_id})
);
}
...and in main
, use those "promises":
function main() {
return async1("the-id").then(function(result1) {
return async2("the-id").then(function(result2) {
return [result1, result2];
});
});
}
That has the advantage (?) of working with jQuery < v1.8.