node.js - Wrap in promise JavaScript generic function -
this question has answer here:
- how convert existing callback api promises? 14 answers
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,
- how recommended wrap in promise .
- 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
Post a Comment