whathetech Javascript,node.js Javascript Promises using Bluebird

Javascript Promises using Bluebird

In http://whatthetech.co/promises-in-javascriptnode-js/ and http://whatthetech.co/promises-in-javascript-and-node-js-part-2-using-promise-all-and-javascript-map/ we understood what promises are and how to use them. If you are new to promises and have not read my earlier blogs, I suggest you read them now before continuing.

What we did in http://whatthetech.co/promises-in-javascript-and-node-js-part-2-using-promise-all-and-javascript-map/ was use Promise.all to execute multiple promises (from an array) in parallel. but in many situations you might want synchronous execution without the need to chain promises. We can do this using a package called bluebird. Bluebird works perfectly with ES6, so, you do not have to use either this or that but can mix it up.

I am going to build from my previous example and show you how you can execute promises synchronously using bluebird’s mapSeries.

function bluebird_mapSeries() {
    //Create an array of 3 file names which needs to be read and processed
    var fileNames = ['test.txt', 'test1.txt', 'test2.txt'];
    
        //Instead of reading them synchronously, we will use promises to read them asynchronously
        var filePromises = fileNames.map(function(fileName) {
            
            return promiseFun1(fileName).then(sentences=>{
                console.log('Processing file = ', fileName);
                return wordCount(sentences);
            });
        });
    
        require('bluebird').mapSeries(filePromises, function (filePromise) {
            return filePromise;
        }).then(numWords=>{
            console.log('Count of all files = ', numWords);
        })
        .catch(err=> {
            console.log(err);
        })
}
bluebird_mapSeries();


Response:

home@home-home-1:~$ node promises.js 
Processing file =  test.txt
Processing file =  test1.txt
Processing file =  test2.txt
Count of all files =  [ 83, 17713, 247 ]

As you can see, even though it takes more time to process test1.txt, the execution is serial in nature unlike Promise.all.
mapSeries is similar to bluebird’s Promise.each where iteration happens serially.

Tags: , , ,