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

在Javascript异步函数中设置全局变量,javascript,asynchronous,Javascript,Asynchronous,我认为我不了解回调和javascript函数的范围。我试着用一个句子来设置响应,但结果是没有定义 function colorTest(callback) { models.Victim.find({ victimsNumber: victimsNumber, active: true }, function(err, victim_data) { var randColor; // Get the color the person said

我认为我不了解回调和javascript函数的范围。我试着用一个句子来设置响应,但结果是没有定义

    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具有异步调用,因此在调用回调函数之前会进行控制台操作。

这是一个非常常见的问题,请参见此处。简言之,你不能这么做。
colorTest(function(result) {
    response = result;
    console.log("The color response is: " + response);
});