Search code examples
javascriptnode.jspromisebluebirdeventemitter

Using promise instead of events Call back


I'm having the following code, this all code is implemented in specified function myFunc, I need that the all function will finish (myFunc) i.e. when the file was extracted successfully/or not to return some status (success/ error).

var myFunc = () => {

var DecompressZip = require('decompress-zip');
var unzipper = new DecompressZip(filename)

unzipper.on('error', function (err) {
    console.log('Caught an error');
});

unzipper.on('extract', function (log) {
    console.log('Finished extracting');
});

unzipper.on('progress', function (fileIndex, fileCount) {
    console.log('Extracted file ' + (fileIndex + 1) + ' of ' + fileCount);
});

unzipper.extract({
    path: 'some/path',
    filter: function (file) {
        return file.type !== "SymbolicLink";
    }
});

};

Since this open source is working with event this is a problem (to get return status...) my intention is to change it to promise by promisify or like following:

   var myFunc = () => {
    
   return new Promise(function(resolve, reject) {
    var DecompressZip = require('decompress-zip');
    var unzipper = new DecompressZip(filename)
    
    unzipper.on('error', function (err) {
        console.log('Caught an error');
        reject();
    });
    
    unzipper.on('extract', function (log) {
        console.log('Finished extracting');
        resolve();
    });
    
    unzipper.on('progress', function (fileIndex, fileCount) {
        console.log('Extracted file ' + (fileIndex + 1) + ' of ' + fileCount);
    });
    
    unzipper.extract({
        path: 'some/path',
        filter: function (file) {
            return file.type !== "SymbolicLink";
        }
    });
    
    };

My questions are:

  1. Since I'm not too expert in JS Does it make sense to convert the events to promise?
  2. There is other good solution which I can use for the use-case?

This is the OP https://github.com/bower/decompress-zip


Solution

  • Converting events to promises only makes sense when you are absolutely positive that the "end" event will only fire once.

    So in this case, yes, what you are suggesting for the implementation should work (assuming I understand your code correctly).