开发者

Variable visibility in callbacks functions

开发者 https://www.devze.com 2023-01-12 02:45 出处:网络
I did this function for get resu开发者_如何学编程lts of a query directly in an useful datastructure. The problem is the follow: in the first console.log() call , inside the callback function, the stor

I did this function for get resu开发者_如何学编程lts of a query directly in an useful datastructure. The problem is the follow: in the first console.log() call , inside the callback function, the stored_data var contains the exact results, in the second console.log() call the stored_data variable looks like not initialized. Suggestions?? Below the code:

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;
    }


I have just remembered that the function doesn't wait the end of the callback execution, for wait the callback end just do a little change to the code:

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;
        }
      }
0

精彩评论

暂无评论...
验证码 换一张
取 消