0

This question may sound stupid, but im trying for an hour or so but couldnt achieve it. Im trying to set values to global variable and im failing. I know its with the concept of scope. I need to identify where i went wrong.. any help is highly appreciated. Thanks.

router.get("/details/:user_id", function(req, res) {


var userId = req.params.user_id;
var sql1 = "SELECT * FROM MOBILE_USERS WHERE ID = ?";
var sql2 = "SELECT * FROM USER_PROFILE WHERE UID  = ?";
var globalArray= null;
//FUNCTION 1
db.getData(sql1,[userId], function(err, results) { //CALLBACK FN
    if(err) { res.status(500).send("Server Error"); return;}
    // Respond with results as JSON
    if(results.length >0) {
      globalArray = results; //set for json array

    }else{
        res.json(0);
    }

});
 FUNCTION 2
db.getData(sql2,[userId],function(err, results) { // Call back function
    if(err) { res.status(500).send("Server Error"); return;}
    // Respond with results as JSON 
    if(results.length >0) {
        globalArray.push(results[0]); //push new values from second function
    }else{
        res.json(0);
    }

});
res.json(globalArray); //send JSON array -> THIS SHOULD CONTAIN VALUES FROM BOTH FUNCTION 1 and 2

});

Pavan
  • 79
  • 11
  • 1
    Your `db.getData()` functions are **asynchronous**. The data won't be there until the database operation completes and the callback is invoked, but the call to `db.getData()` returns immediately. – Pointy Oct 14 '15 at 18:52
  • @Juhana so no chance of me saving data to a single global variable and passing it to client? – Pavan Oct 14 '15 at 18:55
  • Yes there is, but you'll have use a different approach. Read the duplicate. – JJJ Oct 14 '15 at 18:58

0 Answers0