2016-12-13 63 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但但,但容易代表! –