处理慢回调函数

时间:2016-12-13 22:22:25

标签: javascript jquery ajax

从文本文件中获取数据时,似乎需要一段时间。使用第一个console.log结果是未定义的,等待一段时间然后运行console.log数据显示。

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

一旦回调完成,我将如何仅运行代码?

1 个答案:

答案 0 :(得分:1)

只需将console.log()移动到“完成”回调函数中,因为您无法准确知道何时或是否完成。这就是“完成”回调函数的要点 - 推迟在成功调用之后需要完成的工作。

JavaScript promises(或JQuery deferreds)也可用于断开回调与初始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);