Wrap in promise JavaScript generic function

This question already has an answer here:

  • How do I convert an existing callback API to promises? 17 answers

  • 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!

    链接地址: http://www.djcxy.com/p/55528.html

    上一篇: 我可以将回调转换为承诺吗?

    下一篇: 包装在承诺的JavaScript通用功能