簡體   English   中英

在Javascript異步函數中設置全局變量

[英]Setting Global Variable within Javascript Asynchronous function

我不認為我理解回調和我的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(function(result) {
    response = result;
    console.log("The color response is: " + response);
});

這就是你想要的。

您希望在響應發生時調出響應。

你只是在功能之后安慰。 但是,由於colorTest具有異步調用,因此在調用回調函數之前進行安慰。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM