Nathan
Nathan

Reputation: 2387

NodeJS: How do I perform an action after multiple asynchronous functions have completed?

Beginner here. I'm starting to realize that the way I'm using asynchronous functions may not be fully taking advantage of there asynchronous nature.

I do stuff like this:

fs.readFile(file, function(err, data){
  fs.readAnotherFile(anotherFile, function(err, data){
      doThisAfterBothHaveLoaded();
    });
  })
})

But if I'm waiting for one thing to be done before starting the other, isn't that kind of defeating the purpose of it being asynchronous?

So how would I go about doing something like this?:

fs.readfile(file, function(err, data){
  doThisAfterBothHaveLoaded();
});

fs.readAnotherFile(anotherFile, function(err, data){
  doThisAfterBothHaveLoaded();
});

Where the function in the callback isn't called until after both have loaded?

Upvotes: 0

Views: 602

Answers (3)

Ananth
Ananth

Reputation: 4397

Depending on our requirements, we may need to wait for one operation to complete before we can start another operation.

But in your case, if the two operations are not related to each other, and you want to perform some action after both of them are complete, then check the async module.

Using that, you can write:

async.each(['file1.txt', 'file2.txt'], function (filename, cb) {
    fs.readFile(filename, function (err, data) {
        if (err) {
            return cb(err);
        }
        console.log("Reading " + filename + " complete!");
        // do something with data
        console.log(data);
        cb(null);
    });
}, function (err) {
    console.log("Reading both files is complete");
});

Upvotes: 3

binariedMe
binariedMe

Reputation: 4329

var i = 0;
fs.readfile(file, function(err, data){
if(i==1) doThisAfterBothHaveLoaded();
else i++
});

fs.readAnotherFile(anotherFile, function(err, data){
if(i==1) doThisAfterBothHaveLoaded(); 
else i++;
});

Upvotes: 1

Duncan
Duncan

Reputation: 95652

Use promises. Something like:

var Promise = require('promise');
var read = Promise.denodeify(fs.readFile);

var p1 = read(file);
var p2 = read(anotherFile);
Promise.all([p1, p2])
.then(function(res) { doThisAfterBothHaveLoaded(); });

See https://www.npmjs.com/package/promise

Upvotes: 1

Related Questions