简体   繁体   中英

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);
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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM