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

时间:2015-05-30 23:07:21

标签: 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
        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);

1 个答案:

答案 0 :(得分:2)

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

这就是你想要的。

您希望在响应发生时调出响应。

你只是在功能之后安慰。但是,由于colorTest具有异步调用,因此在调用回调函数之前进行安慰。