weixin_33735676 2016-05-27 18:47 采纳率: 0%
浏览 57

对于循环,XHR,范围

I'm really stuck with what maybe a scoping issue. Can anyone here please help me find fault with this snippet?

So I have something called surveys that are associated with a questiongroup. And i'm trying to loop through surveys to get data about the associated questiongroup except I'm really lost on where I should scope a question group.

The first function in snippet below logs qg as 'undefined' returned from the second function.

function loadData() {
  var params = {};
  var surveyURL = "surveys/";
  var surveys, qg;
  var survey_ids = [];
  // this below calls the URL 
  var $surveyXHR = klp.api.do(surveyURL, params);
  // this below is essentially $.ajax.done()
  $surveyXHR.done(function(data) {
    surveys = data["features"];
    for(var each in surveys) {
      qg = getSurveysQuestionGroup(surveys[each]["id"]);
      console.log(qg);
      // surveys[each]["created_by"] = qg["created_by"]["first_name"]
    }
    console.log(surveys);
  });

}

function getSurveysQuestionGroup (surveyId) {
  var params = {};
  var qg;
  var qgURL = "surveys/"+ surveyId + "/questiongroups/";
  var $qgXHR = klp.api.do(qgURL, params); 
  $qgXHR.done(function(data) {
        qg= data["features"];
        //console.log(qg);
        return(qg);
  });
}
  • 写回答

2条回答 默认 最新

  • weixin_33701617 2016-05-27 19:05
    关注

    You're misunderstanding how ajax works. Your function getSurveysQuestionGroup could be rewritten like this:

    function getSurveysQuestionGroup (surveyId) {
      var params = {};
      var qg;
      var qgURL = "surveys/"+ surveyId + "/questiongroups/";
      var $qgXHR = klp.api.do(qgURL, params); 
      $qgXHR.done(processQgXHR);
      return; // THIS is what you are getting back in loadData!
    }
    
    function processQgXHR(data) {
      var qg = data["features"];
      return(qg); // not being used!
    }
    

    You'll need to refactor your code. Ideally, you want to take action from inside the ajax callback function itself, not using return values. Ajax and return values typically don't mix well.

    If you're familiar with multi-threaded programming, think of an ajax request as creating a new thread, not a function call.

    评论

报告相同问题?