Setting a Global Variable in Javascript Asynchronous Function

I don't think I understand callbacks and the scope of my javascript function. I'm trying to install an answer with a suggestion, 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);

      

+3


source to share


1 answer


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

      

Is this what you want.



You want to disable the response when the response happens.

You just consoled yourself after this function. But since colorTest has asynchronous calls, the leak occurs before the callback is called.

+2


source







All Articles