Bikash Dash Bikash Dash - 7 months ago 9
Javascript Question

Assigning an object of outer function from inside of inner function javascript

I can't assign the value of result in the inner function . any ways to do that ?
I can console log the result variable inside the function . Someone advised me to do with promises . I have no idea how to do that . I am a beginner of node and express.

router.post("/register",function(req,res){
var firstName = req.body.firstName;
var lastName = req.body.lastName;
var email = req.body.email;
var mobile = req.body.email;
var oauthProvider = req.body.oauthProvider;
var oauthId = req.body.oauthId;
var userType = req.body.type;
if (userType === undefined) {
userType = 1;
}
var result = {};
result.message = "Not edited";
connection.model.query("SELECT `id` FROM `users`" + "WHERE users.email = ?",[email],function(err,rows){

if(err !== null )
{
result.error = err;
result.success = false;
} else if(rows.length >= 1){
result.success = false;
result.message ="User already exists" ;
}
else
{
connection.model.query("INSERT INTO `users`(`first_name`,`last_name`,`email`,`mobile`,`password`,`user_type`) VALUES (?,?,?,?,?,?)",[firstName,lastName,email,mobile,password,userType],function(err,res){
if(err !== null )
{
result.error = err;
result.success = false;
}else{
var user = {
id : res.insertId,
first_name : firstName,
email : email
};

connection.model.query("INSERT INTO `users_profile`(`user_id`) VALUES (?)",[user.id],function(err,profileres){
if(err !== null )
{
result.error = err;
result.success = false;
}else{

if(oauthProvider != undefined && oauthId != undefined){
connection.model.query("INSERT INTO `users_oauth`(`user_id`, `provider`, `provider_uid`) VALUES (?,?,?)",[user.id,oauthProvider,oauthId],function(err,oauthres){
if(err !== null )
{
result.error = err;
result.success = false;
result.message = "couldn't create oauth user";
}
});

}
var token = jwt.sign(user, SECRET, {
expiresIn: "15d" // expires in 15 days
});

// return the information including token as JSON
result.success = true;
result.message = 'successfully registered';
result.token = token;


}

});
}
});

}

res.setHeader('content-type','text/json');
res.send(json_encode(result));


});

});

Answer

U should send the response inside the callback as follows:

result.success = true;
 result.message = 'successfully registered'; 
 result.token = token;
 res.setHeader('content-type','text/json'); 
 res.send(json_encode(result));

instead of sending response outside the callback.

EDIT: ok i got it.. its taking your query res, so change the code a follows:

router.post("/register",function(httpreq,httpres){

result.success = true;
     result.message = 'successfully registered'; 
     result.token = token;
     httpres.setHeader('content-type','text/json'); 
     httpres.send(json_encode(result));