2016-12-13 155 views
0

從文本文件中獲取數據時,似乎需要一段時間。使用第一個console.log,結果未定義,等待一段時間後,然後運行console.log數據顯示。處理緩慢的回調函數

var msg; 
$.get("./whazzup.txt", function(text) { 
    msg = text; 
}); 
console.log(msg); 
setTimeout(function(){ console.log(msg); }, 3000); 

一旦回調完成後,我將如何處理運行代碼?

+0

*「一旦回調完成,我將如何處理運行代碼?」*通過將代碼放入回調中? –

回答

1

只需將console.log()移動到「完成」回調函數中,因爲您無法確切知道何時完成。這是「完成」回調函數的要點 - 推遲成功調用後需要完成的工作。可以使用JavaScript承諾(或JQuery延遲)來將回調與最初的AJAX請求斷開連接,以獲得更大的靈活性,但AJAX的本質保持不變。

$.get("./whazzup.txt", function(text) { 
    // This function will only be executed when the AJAX call has successfully completed 
    msg = text; 
    console.log(msg); 
}); 

// This one was working, because you are basically telling the JavaScript 
// runtime to wait 3 seconds (at least) before writing the message and by 
// that time the AJAX call has completed. But, this technique is not 
// reliable because there may be times when the AJAX call hasn't completed 
// after 3 seconds. You just can't know how long it will take. 
setTimeout(function(){ console.log(msg); }, 3000); 
+2

來吧斯科特,你知道這個問題已被問了很多時間... –

+0

@MikeMcCaughan但但,但容易代表! –