只需將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);
*「一旦回調完成,我將如何處理運行代碼?」*通過將代碼放入回調中? –