简体   繁体   English

在Javascript异步函数中设置全局变量

[英]Setting Global Variable within Javascript Asynchronous function

I dont think I understand callbacks and the scope of my javascript function. 我不认为我理解回调和我的javascript函数的范围。 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. 但是,由于colorTest具有异步调用,因此在调用回调函数之前进行安慰。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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