回调函数中的变量可见性
问题描述:
我做了这个函数直接在有用的数据结构中获取查询结果。问题在于:在第一个console.log()调用中,在回调函数内部,stored_data var包含确切的结果,在第二个console.log()调用stored_data变量看起来像未初始化。建议? 代码如下:回调函数中的变量可见性
function dojo_query_mysql(query_string) {
//The parameters to pass to xhrPost, the message, and the url to send it to
//Also, how to handle the return and callbacks.
var stored_data;
var raw_data = new Object;
var xhrArgs = {
url: "query.php",
postData: query_string,
handleAs: "text",
load: function(data) {
raw_data = dojo.fromJson(data);
stored_data = new dojo.data.ItemFileReadStore({data: raw_data});
console.log(stored_data);
},
error: function(error) {
//We'll 404 in the demo, but that's okay. We don't have a 'postIt' service on the
//docs server.
//stored_data = error;
}
}
//Call the asynchronous xhrPost
var deferred = dojo.xhrPost(xhrArgs);
console.log(stored_data);
return stored_data;
}
答
我刚才记住的是,函数不会等待回调执行结束,为等待回调结束只是做了一点改变代码:
var xhrArgs = {
url: "query.php",
sync: true, // THIS IS FORCE THE SYNCRONIZATION BETWEEN THE CALLBACK AND THE CODE
postData: query_string,
handleAs: "text",
load: function(data) {
raw_data = dojo.fromJson(data);
stored_data = new dojo.data.ItemFileReadStore({data: raw_data});
console.log(stored_data);
},
error: function(error) {
//We'll 404 in the demo, but that's okay. We don't have a 'postIt' service on the
//docs server.
//stored_data = error;
}
}
你应该**从不**使用'sync:true',除非它绝对是必要的。它击败了XHR的许多目的,并且从AJAX中取出了第一个A。理想情况下,任何依赖XHR结果的代码都应该在'load'回调中,或者使用'then'(或Dojo 2011-01-13 00:54:06