1

I am new to javascript async programming and i have a basic issue where I have a Set of code where i am doing two separate DB calls on basis of request body params . These are two methods which does a DB Call and returns a Promise

  1. validateExam
  2. validateUserExists

I want to store resullts from async call to this myExam variable and then return it in response .

getExam: function(req, res) {
    var myExam = {};
    var coupon = req.body.coupon;
    var email = req.body.email;


    async.series([
        function(callback) {
            validateExam(coupon)
                .then(function(success) {

                    callback(null, success);
                });
        },
        function(callback) {
            validateUserExists(email)
                .then(function(result) {
                    callback(null, result);
                })
        }
    ], function(error, results) {
        myExam.res = results;

    });


    res.json({
        "status": 400,
        "message": myExam
    });
},
Sanjay
  • 117
  • 4
  • 13
  • res.json should be inside the callback function of the async.series. Right below myExam.res = results – yBrodsky May 23 '17 at 16:04

1 Answers1

1

You can't return an asynchronously retrieved value from your function. Your function returns BEFORE the async operation is even done. Instead, you need to communicate the return value back to the caller via either a returned promise or by passing in a callback that you can call when the async operation is done. For more info on the details of that, see: How do I return the response from an asynchronous call?.

In addition, using the async library to manage two promise operations is very odd. Promises have all the tools built in themselves to manage asynchronous operations so if your core operations are already returning promises, you should just use those promises directly and not involve the async library.

In looking at your code, it appears that validating the exam and validating the user are independent operations and you can run them in a parallel and use Promise.all() to know when both promises are done.

You can do something like this:

getExam: function(req, res) {
    var coupon = req.body.coupon;
    var email = req.body.email;

    Promise.all([validateExam(coupon), validateUserExists(email)]).then(function(results) {
        // results is a two element array that contains the two validation results
        // send your response here based on the results array (not clear to me exactly what you want here)
        res.json(...);
    }).catch(function(err) {
        // return some sort of error response here
        res.status(500).json(...);
    });
},
jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • Actually my problem is how are we going to write business logic , lets say i have a use Case where i need to have multiple DB calls and those db call are synchronus one after another . Do you suggest to write down in Same way you mentioned above ? – Sanjay May 24 '17 at 06:12
  • @Sanjay-Dev - Perhaps you're new here, but this site doesn't work well as a tutorial site to ask a question and try to learn a general topic. Instead, you need a specific problem, you post the code you're trying to get to work and we help you with a specific solution. That's what I did for the code you posted in your answer. Promises can be used to coordinate asynchronous operations in any way you need to (parallel, in sequence or any combination). I offered you an answer with operations running in parallel because the code you showed does not require sequencing of those operations. – jfriend00 May 24 '17 at 06:18
  • @Sanjay-Dev - Running asynchronous operations in parallel is nearly always faster than running them in sequence when parallel operation is feasible. There are lots of answers here on stack overflow already about how to sequence operations using promises. Here's one answer about sequencing async operations: https://stackoverflow.com/questions/29880715/how-to-synchronize-a-sequence-of-promises/29906506#29906506. There are many others. If you need help sequencing asynchronous operations, then please post a new question with your actual code that needs to be synchronized. – jfriend00 May 24 '17 at 06:20