Over a million developers have joined DZone.

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

Bugsnag monitors application stability, so you can make data-driven decisions on whether you should be building new features, or fixing bugs. Learn more.

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){
        return readFileAsync(file, {encoding: 'utf-8'});
        return execDbAsync(query);
}, 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'});
        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)

Monitor application stability with Bugsnag to decide if your engineering team should be building new features on your roadmap or fixing bugs to stabilize your application.Try it free.

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 }}