Wrap it in a promise. General JavaScript Function

How can I wrap a function that can work with / a -sync sync inside with a promise?

I call a function like the following

action[fn](req, res); 

in the fn function (in the following example) is executed internally (I use a dynamic call for each function) sync or a-sync, as shown below,

  • As it is recommended to wrap it in a promise.
  • How to handle errors, if any ...

I am using 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"); } 
+6
source share
1 answer

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, the promise will be resolved after the req end event, and then res.end, but I recommend creating another method to complete the response and work with the promise from the method launch. Good luck

+1
source

All Articles