只需将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);
*“一旦回调完成,我将如何处理运行代码?”*通过将代码放入回调中? –