Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrap in promise JavaScript generic function [duplicate]

How can I wrap a function which can have sync/a-sync functionality inside with promise ?

I've call to the function like following

action[fn](req, res);

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

  1. How its recommended to wrap it in promise .
  2. How to 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 to update data file")
        });
        res.end("File " + filePath + " saved successfully");
    }
like image 836
07_05_GuyT Avatar asked Jul 14 '15 09:07

07_05_GuyT


People also ask

Does Promise all use multiple threads?

Often Promise. all() is thought of as running in parallel, but this isn't the case. Parallel means that you do many things at the same time on multiple threads. However, Javascript is single threaded with one call stack and one memory heap.

What is the problem with promises in Javascript?

Promises co-mingle rejected promises and unintended runtime exceptions. Apart from how the API is structured - promises have another major flaw: they treat unintentional native runtime exceptions and intentional rejected promises - which are two drastically different intentions - in the same "path".

Does Promise run in parallel?

Unlike callbacks, which are always executed sequentially (one after another), you have options for how to run multiple promises. Promises provide you with several options for how you can run promises in parallel.

Which is faster Promise or callback?

So from my findings i assure you ES6 promises are faster and recommended than old callbacks. I recommend to get a common understanding of JS event loop.


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

like image 109
siavolt Avatar answered Oct 16 '22 23:10

siavolt