2015-05-30 86 views
3

我不認爲我理解我的javascript函數的回調函數和範圍。我試圖用一個句子來設置答案,但事實證明這是未定義的。在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

這是非常常見的問題,請參閱http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call。用幾句話說,你不能那樣做。 – elclanrs

回答

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

這是你想要的。

您希望在響應發生時安慰響應。

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