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

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

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)

Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.

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

Published at DZone with permission of Can Ho, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}