3

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);
drewg23333
  • 45
  • 5
  • 1
    This is very common question, see here http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call. In few words, you can't do that. – elclanrs May 30 '15 at 23:08

1 Answers1

2
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.