Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting Global Variable within Javascript Asynchronous function

I dont think I understand callbacks and the scope of my javascript function. I am trying to set the response with a sentence, but it turns out to be undefined.

    function colorTest(callback) {
      models.Victim.find({ victimsNumber: victimsNumber, active: true }, function(err, victim_data) {
        var randColor;
        // Get the color the person said
        if (victim_data[0].favColor == null) {
        // If null choose a 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 is *"+ randColor +"*. You will continue to get our Cat Facts *daily*.");
    } else if (theSMS == victim_data[0].favColor) {
      callback("Good job! Step 2 verification! What is the favorite animal you signed up with?");
    } else {
      callback("INCORRECT. You're favorite color is *"+ victim_data[0].favColor +"*. You will continue to get our Cat Facts *daily*.");
    }
    // Set the color the person said as their 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);
like image 399
drewg23333 Avatar asked Jun 17 '26 08:06

drewg23333


1 Answers

colorTest(function(result) {
    response = result;
    console.log("The color response is: " + response);
});

This is what you want.

You want to console out the response when the response happens.

You were just consoling after the function. But, since colorTest has asynchronous calls, the consoling occurs before the callback function is invoked.

like image 118
BeagleBreath Avatar answered Jun 19 '26 21:06

BeagleBreath



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!