7

How can I wrap a function which can have sync/a-sync functionality inside with promise ?

I've call to the function like following

action[fn](req, res);

in function fn(in following example) is run can have inside (I use dynamic call for every function) sync or a-sync like below example,

  1. How its recommended to wrap it in promise .
  2. How to handle errors if any...

I use nodeJS application

 run: function (req, res, filePath) {
        var writeStream = fs.createWriteStream(fileRelPath, {flags: 'w'});
        req.pipe(writeStream);
        req.on("end", function () {
            console.log("Finish to update data file")
        });
        res.end("File " + filePath + " saved successfully");
    }
phuzi
  • 12,078
  • 3
  • 26
  • 50
07_05_GuyT
  • 2,787
  • 14
  • 43
  • 88

1 Answers1

1

for example we can use Q libary and defer, something like this:

run: function (req, res, filePath) {
        var d = Q.defer();

        var writeStream = fs.createWriteStream(fileRelPath, {flags: 'w'});
        req.pipe(writeStream);
        req.on("end", function () {
            console.log("Finish to update data file");
            d.resolve();
        });

        req.on("error", function (err) {
            d.reject(err);
        });



        return d.promise.then(function(){
            res.end("File " + filePath + " saved successfully");
        }).catch(function(err){
            //handle error
        })
    }

In this code promise will resolve after req end event, and then res.end, but I recommend create another method for finish response and work with promise from method run. Good luck!

Roamer-1888
  • 19,138
  • 5
  • 33
  • 44
siavolt
  • 6,869
  • 5
  • 24
  • 27