Setting Global Variable within Javascript Asynchronous function -
i dont think understand callbacks , scope of javascript function. trying set response sentence, turns out undefined.
function colortest(callback) { models.victim.find({ victimsnumber: victimsnumber, active: true }, function(err, victim_data) { var randcolor; // color person said if (victim_data[0].favcolor == null) { // if null choose random color randcolor = colors[math.floor(math.random() * colors.length)]; while (randcolor == thesms) { randcolor = colors[math.floor(math.random() * colors.length)]; } callback("incorrect. you're favorite color *"+ randcolor +"*. continue our cat facts *daily*."); } else if (thesms == victim_data[0].favcolor) { callback("good job! step 2 verification! favorite animal signed with?"); } else { callback("incorrect. you're favorite color *"+ victim_data[0].favcolor +"*. continue our cat facts *daily*."); } // set color person said new color models.victim.update({ _id: victim_data[0]._id}, {$set: {favcolor: thesms}}, function(err, result) { if (err) { console.log(err); } }); return response; }); } colortest(function(result) { response = result; }); console.log("the color response is: " + response);
colortest(function(result) { response = result; console.log("the color response is: " + response); }); this want.
you want console out response when response happens.
you consoling after function. but, since colortest has asynchronous calls, consoling occurs before callback function invoked.
Comments
Post a Comment