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){
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
source share