How to Properly Use Promises
Promises are wonderful - they enable developers to avoid cascading callbacks and make the code way clearer.
However, when you work with promises, you should avoid as much as possible creating new promises for each new request and managing them yourself.
Let’s examine the following code:
var makeRequest = function(options){
var deferred = Q.defer();
request.call(options, function(err, result){
if(err){
return deferred.reject(err);
}
deferred.resolve(result);
});
return deferred.promise;
};
var getRequest = function(url){
var deferred = Q.defer();
var options = {
method: "GET",
url: url
};
makeRequest(options)
.then(function(result){
deferred.resolve(result);
})
.catch(function(error){
deferred.reject(error);
})
;
return deferred.promise;
};
var getMyAccount = function(accountId){
var deferred = Q.defer();
getRequest('/account/'+accountId)
.then(function(result){
deferred.resolve(result);
})
.catch(function(error){
deferred.reject(error);
})
;
return deferred.promise;
};
The issue here is that a new promise is created in each function, but it is resolved depending on another sub-promise resolution. This development practice makes unnecessary code, more difficult to read and less efficient. We should refactor it into the following, more promise-friendly, version:
var makeRequest = function(options){
var deferred = Q.defer();
request.call(options, function(err, result){
if(err){
return deferred.reject(err);
}
deferred.resolve(result);
});
return deferred.promise;
};
var getRequest = function(url){
var options = {
method: "GET",
url: url
};
return makeRequest(options);
};
var getMyAccount = function(accountId){
return getRequest('/account/'+accountId);
};
The second version avoids creating a new promise at each level, thus reducing the overhead, the possibility to make bugs or to handle errors, and is much more readable. And it works the same.
Contributors
Pierre Killy
Writing code since the age of eight, Pierre's love of technology has led him to earn a master's degree in computer science. From pure engineering to building processes for CI and CD on heavy-loaded infrastructure at Viadeo (100+ production servers), he co-founded a startup company as CTO. Pierre is a dedicated, enthusiastic leader, a creative solution-maker and a web engineering expert with more than a decade of experience.
Show More