node.js - Wrap in promise JavaScript generic function -


this question has answer here:

how can wrap function can have sync/a-sync functionality inside promise ?

i've call function following

action[fn](req, res); 

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

  1. how recommended wrap in promise .
  2. how 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 update data file")         });         res.end("file " + filepath + " saved successfully");     } 

for example can use q libary , defer, 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 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 code promise resolve after req end event, , res.end, recommend create method finish response , work promise method run. luck!


Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

jquery - javascript onscroll fade same class but with different div -