Sanjay
Sanjay

Reputation: 115

How do we sent data to local variable in node js async with DB Calls

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
    });
},

Upvotes: 1

Views: 83

Answers (1)

jfriend00
jfriend00

Reputation: 707656

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(...);
    });
},

Upvotes: 1

Related Questions