Here are a couple of possibilities. Since this question has an element of personal taste for it, you may or may not like what you see!
(Login - I have not tested this code)
Option 1 - Use a wrapper for resolve and reject . This adds โnoiseโ in the form of auxiliary functions, but improves the rest.
var resolve = function (deferred, ob) { return function () { deferred.resolve(ob); }; }; var reject = function (deferred, ob) { return function () { deferred.reject(ob); }; }; exports.verify = function(data) { var deferred = Q.defer(); postToService(data, "https://production-url.com") .then(resolve(deferred, body)) .fail(function(err) { if (err.code === 21007) { postToService(data, "https://sandbox-url.com") .then(resolve(deferred, body)) .fail(reject(deferred, err)); } else { deferred.reject(err); } }); return deferred.promise; };
Option 2 - Use binding. This has the advantage of using existing JS functions, but when creating callbacks, you have duplicate references to deferred .
exports.verify = function(data) { var deferred = Q.defer(); postToService(data, "https://production-url.com") .then(deferred.resolve.bind(deferred, body)) .fail(function(err) { if (err.code === 21007) { postToService(data, "https://sandbox-url.com") .then(deferred.resolve.bind(deferred, body)) .fail(deferred.reject.bind(deferred, err)); } else { deferred.reject(err); } }); return deferred.promise; };
Option 3 - Use the bind and 'handle methods' (minor change to # 2).
exports.verify = function(data) { var deferred = Q.defer(); var resolve = deferred.resolve; var reject = deferred.reject; postToService(data, "https://production-url.com") .then(resolve.bind(deferred, body)) .fail(function(err) { if (err.code === 21007) { postToService(data, "https://sandbox-url.com") .then(resolve.bind(deferred, body)) .fail(reject.bind(deferred, err)); } else { deferred.reject(err); } }); return deferred.promise; };
Option 4 - The monkey patch is delayed.
function patch(deferred) { deferred.resolveFn = function (ob) { return function () { deferred.resolve(ob); }; }; deferred.rejectFn = function (ob) { return function () { deferred.reject(ob); }; }; return deferred; } exports.verify = function(data) { var deferred = patch(Q.defer()); postToService(data, "https://production-url.com") .then(deferred.resolveFn(body)) .fail(function(err) { if (err.code === 21007) { postToService(data, "https://sandbox-url.com") .then(deferred.resolveFn(body)) .fail(deferred.rejectFn(err)); } else { deferred.reject(err); } }); return deferred.promise; };