Parallel asynchronous functions with NodeJS promise

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

  if (err) ...

we can instead write


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];
  return Model.query({id:id});

Example 2: we want to run 2 different database queries in parallel and process the result at once.

    return Model.queryOne();
    return Model.queryTwo();
  // 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.

This entry was posted in Programming and tagged , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s