Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Executing Async Tasks Serially With Array#Reduce

DZone's Guide to

Executing Async Tasks Serially With Array#Reduce

Want to know how to execute async tasks serially without needing to use the async#reduce or async#series libraries. Let me show you how with the array#reduce method...

· Web Dev Zone ·
Free Resource

Deploying code to production can be filled with uncertainty. Reduce the risks, and deploy earlier and more often. Download this free guide to learn more. Brought to you in partnership with Rollbar.

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

  • The tool will read a list of SQL scripts and execute them serially one after another.
  • Each script will run once the 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 an additional library, this executing async tasks serially problem can be solved by using the 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());


The above code will return a Promise which:

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

Compared to using async#reduce, using the built-in 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)

Deploying code to production can be filled with uncertainty. Reduce the risks, and deploy earlier and more often. Download this free guide to learn more. Brought to you in partnership with Rollbar.

Topics:
array ,problem ,library ,migration ,tasks ,tool

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}