回调函数中的可变可见性

时间:2010-08-19 20:41:35

标签: dojo object return-value callback

我使用此函数直接在有用的数据结构中获取查询结果。问题是如下:在第一个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;
    }

1 个答案:

答案 0 :(得分:0)

我刚才记得该函数没有等待回调执行结束,等待回调结束只是对代码做了一点改动:

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