Eric
Eric

Reputation: 488

How can I know when a series of functions have all finished their exeution in Node js?

Here's a code snippet

var zip = new require('node-zip')(data, {base64: false, checkCRC32: true});

for (var i in zip.files) {
    fs.writeFile(path.join(to, i), zip.files[i], function(err) {
        if (err) { error = err; }
    });
}

Is there any way to be aware of when they're all executed?

Upvotes: 0

Views: 38

Answers (2)

Daniel
Daniel

Reputation: 38849

A very commonly used module for handling many types of asynchronous operations is the async.js module. In fact, it's the most depended upon module in NPM behind underscore.

In your case I recommend the async.series function.

var async = require('async');
var zip = new require('node-zip')(data, {base64: false, checkCRC32: true});

async.eachSeries(zip.files, function(file, cb) {
    fs.writeFile(path.join(to, i, file, function(err) {
      if(err) return cb(err);
      cb();
    });
  },
  function(err) {
    if(err) throw err;
  }
);

Upvotes: 1

RobW
RobW

Reputation: 10621

Common problem. Try each-async which abstracts the counter method so you don't have to write it yourself. You can also look at promises, but that might not work if your code doesn't use promises already; it can be weird to mix promises and callback code.

Upvotes: 0

Related Questions