Suppose that we’re assigned a task of writing a migration tool for a database with following requirements:

  • The tool will read a list of sql scripts and execute them serially one after another.
  • Each script will run once previous script has completed.
  • If any script execution fails, no more scripts will execute.

This can be done by using a library such as async#reduce( or async#series )

async.reduce(files, Promise.resolve(), function(prevPromise, file, callback){
    prevPromise.then(function(){
        return readFileAsync(file, {encoding: 'utf-8'});
    }).then(function(query){
        return execDbAsync(query);
    }).then(function(data){
        callback(data);
    });
}, function(err, result){

});

Without using additional library, this executing async tasks serially problem can be solved by using Array#reduce method:

files.reduce(function(prevPromise, curr, curIdx, arr){
    return prevPromise.then(function(){
        return readFileAsync(curr, {encoding: 'utf-8'});
    })
    .then(function(query){
        return execDbAsync(query);
    });
}, Promise.resolve());

Above code will return a Promise which:

  • gets resolved when all chaining promises get resolved.
  • gets rejected when any of chaining promises gets rejected.

Comparing to using async#reduce, using builtin Array#reduce method has some benefits:

  • No additional library needed
  • No callback
  • Less code as we don’t need to explicitly call “callback (data)” to notify a task completion

Execution order looks like bellow:

read (script 1)—> exec (script 1)—> read (script2)—> exec (script 2)—>…–> read (script n)—> exec (script n)

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s