函数调用另一个而无需等待完成

时间:2015-10-23 02:54:25

标签: javascript jquery

在我的方法feedContactCategorySelection中,我想等待assignContactCategoryToLocal调用完成后再继续运行其余的代码

feedContactCategorySelection();

function feedContactCategorySelection(){

  assignContactCategoryToLocal();

  var category = sessionStorage.getItem("category");

  category = JSON.parse(category);
  for (var i = 0; category["data"].length; i++) {
    //....
  }
}


function assignContactCategoryToLocal() {

  var category = sessionStorage.getItem("category");
  if (category == null) {
    $.ajax({
        url: 'http://localhost:8080/rest/contact/category',
        type: 'GET',
        success: function (json) {
            sessionStorage.setItem("category", JSON.stringify(json));
        }
    });
}

4 个答案:

答案 0 :(得分:2)

您可以将回调函数传递给assignContactCategoryToLocal(),这样只有在完成ajax后才能继续运行代码。像这样:

feedContactCategorySelection();

function feedContactCategorySelection() {
    // Do anything here before running the ajax
    // For instance, get category and pass it to the assignContact...
    var category = sessionStorage.getItem("category");
    ...
    assignContactCategoryToLocal(category, myCallbackFunction);
}

function myCallbackFunction(category) {
    category = JSON.parse(category);
    for (var i = 0; category["data"].length; i++) {
        ....
    }
}

function assignContactCategoryToLocal(category, callback) {

    if (category == null) {
      $.ajax({
          url: 'http://localhost:8080/rest/contact/category',
          type: 'GET',
          success: function (json) {
              sessionStorage.setItem("category", JSON.stringify(json));
              // Now that it is done and successful, run the rest...
              callback(category);
          }
      });
    }
}

为了举例,您可以获取一次类别,然后将其传递给函数,这可能有助于了解它们的连接方式。

修改 要解决类别为null的问题,请参阅修订版。

feedContactCategorySelection();

function feedContactCategorySelection() {
    // Do anything here before running the ajax
    // For instance, get category and pass it to the assignContact...
    var category = sessionStorage.getItem("category");
    ...

    // Move the if statement here so it checks the condition earlier.
    if (category === null) {
        assignContactCategoryToLocal(category, myCallbackFunction);
    } else {
        myCallbackFunction(category);
    }
}

function myCallbackFunction(category) {
    category = JSON.parse(category);
    for (var i = 0; category["data"].length; i++) {
        ....
    }
}

function assignContactCategoryToLocal(category, callback) {
    $.ajax({
      url: 'http://localhost:8080/rest/contact/category',
      type: 'GET',
      success: function (json) {
          sessionStorage.setItem("category", JSON.stringify(json));                           
          // Now that it is done and successful, run the rest...
          callback(category);
      }
    });
}

答案 1 :(得分:1)

在这种情况下,请考虑使用Promise

伪码如下:

feedContactCategorySelection();

function feedContactCategorySelection(){

  assignContactCategoryToLocal().then(function(){
    var category = sessionStorage.getItem("category");

    category = JSON.parse(category);
    for (var i = 0; category["data"].length; i++) {
     ....
    }
  })

}

function assignContactCategoryToLocal() {
  return new Promise(function(resolve, reject){
    var category = sessionStorage.getItem("category");
  if (category == null) {
    $.ajax({
        url: 'http://localhost:8080/rest/contact/category',
        type: 'GET',
        success: function (json) {
            sessionStorage.setItem("category", JSON.stringify(json));
            resolve()
        }
        failed:{reject(reason)}
    });
  })    

}

答案 2 :(得分:1)

function feedContactCategorySelection() {    
  // `data` : `sessionStorage.getItem("category")` or response from `$.ajax()`
  assignContactCategoryToLocal().then(function(data) {   
      // if `category` set , return `category` , else set `category`
      var category = sessionStorage.getItem("category") != null 
                     ? sessionStorage.getItem("category") 
                     : sessionStorage.setItem("category", JSON.stringify(data));   
      category = JSON.parse(category);
      for (var i = 0; category["data"].length; i++) {
        //....
      }
  // handle errors, if any, from `$.ajax()` call
  }, function err(jqxhr, textStatus, errorThrown) {
       console.log(textStatus, errorThrown)
  })
}

function assignContactCategoryToLocal() {
  var category = sessionStorage.getItem("category");  
    // if `category` is `null` , return `$.ajax()` response   
    return category == null
       ? $.ajax({
           url: 'http://localhost:8080/rest/contact/category',
           type: 'GET'
         }) 
      : $.when(category)
}

答案 3 :(得分:1)

请检查我是否已添加async: false,等待,直到获得ajax响应。

feedContactCategorySelection();

function feedContactCategorySelection(){

  assignContactCategoryToLocal();

  var category = sessionStorage.getItem("category");

  category = JSON.parse(category);
  for (var i = 0; category["data"].length; i++) {
    //....
  }
}


function assignContactCategoryToLocal() {

  var category = sessionStorage.getItem("category");
  if (category == null) {
    $.ajax({
        url: 'http://localhost:8080/rest/contact/category',
        type: 'GET', 
        async: false,
        success: function (json) {
            sessionStorage.setItem("category", JSON.stringify(json));
        }
    });
}