Long time since I last wrote a post. So recently I’ve been doing NodeJS and meets a cool feature: Promise. Promise is a way to make asynchronous callback look like serial, so instead of writing
doSomething(function(err,obj){ if (err) ... ... doSomethingElse(function(err,obj){...}) });
we can instead write
doSomething() .then(function(obj){...}) .then(function(obj){...}) .catch(function(err){...});
and we can even catch all the errors in one function, that’s neat!
NodeJS library for promise is bluebirdJS. You can learn more about it on the site.
What’s even cooler about promise is the ability to make several asynchronous functions run in parallel. Well not true parallel because NodeJS is single-threaded, but the point is we can run several promises simultaneously and wait until they all finish then continue our code. This is done with bluebird’s Promise.all() function. Promise.all() receives an array of object and the resulting promise will return an array of result for each object.
I’ll give 2 examples.
Example 1: we want to make a database query for several ids in parallel and process the results at once. This can be done with
var ids = [1,2,3,4,5]; Promise.all(ids.map(function(id){ return Model.query({id:id}); })) .then(function(results){...});
Example 2: we want to run 2 different database queries in parallel and process the result at once.
Promise.all([ (function(){ return Model.queryOne(); })(), (function(){ return Model.queryTwo(); })() ]) .then(function(results){ // results[0] contains result of first query // results[1] for second query });
That’s very easy and short. Now imagine how many lines and functions are needed to write the above queries with callback. Promise paradigm is indeed very promising and helpful for asynchronous programming.