jQuery完成后不等待它完成

时间:2016-11-20 19:39:09

标签: javascript jquery

jQuery没有等待它在调用之前完成该功能。

$.when(saveChanges()).done(showSignInPrompt());

我把console.log()放在每个内部,看看哪个是第一个。而且,看哪,后者是第一位的。

我是以错误的方式使用它吗?

这是savechanges的样子:

showSavedNotification_check = 1;

function saveChanges(bypassDeckSave) {
  // bypassDeckSave = undefined - does not bypass
  showSavedNotification_check = 1;
  if(userid != 0) {
    //values in database
    var subjectID = $('.lib_folder_id').val(),
      folderID = $('.lib_subject_id').val();
    if(subjectID == 0 || folderID == 0) { //if database values null, ask for some
      console.log("db deck location not saved, asked for it");
      //values to set to 
      var setFolderID = $('.libDeckLocationModifierDiv .folders li.on').val() + 0,
        setSubjectID = $('.libDeckLocationModifierDiv .subjects li.on').val() + 0;
      if(isNaN(setFolderID) || isNaN(setSubjectID) || setFolderID == 0 || setSubjectID == 0) {
        openDeckLocationDiv();
        showSavedNotification_check = 0;
        return;
      }
    }
  }
  var deck_id = $('.deck_id').val();
  if(deck_id == 0) {
    // create a new deck
    createDeckThenSave();
    return;
  }
  if(userid != 0) {
    //values in database
    var subjectID = $('.lib_folder_id').val(),
      folderID = $('.lib_subject_id').val();
    if(subjectID == 0 || folderID == 0) { //if database values null, ask for some
      //values to set to 
      saveDeckLocation();
    }
  }
  // removes empty rows
  $('.editMain li').each(function() {
    var one = $(this).find('.text1').val(),
      two = $(this).find('.text2').val();
    if(one == "" && two == "") {
      //remove this row and remove value from updateSaveArray + add to delete array
      var currentval = $(this).val();
      var rowid = ".row_" + currentval;
      updateSaveArray = jQuery.grep(updateSaveArray, function(value) {
        return value != currentval;
      });
      $(rowid).remove();
      updateDeleteArray[updateDeleteArray.length] = currentval;
    }
  });
  if(bypassDeckSave == undefined) {
    // save deck info to db
    var deckname = $('.editDeckNameInput').val(),
      cardCount = $('.editMain li.mainLi:visible').length,
      deckTermLanguage = $('.selector.one select').val(),
      deckDefinitionLanguage = $('.selector.two select').val(),
      deckThirdBoxLanguage = $('.selector.three select').val(),
      deckDescription = $('.editMoreDeckOptionsDiv textarea').val();
    if($('.editMoreDeckOptionsSelector .onlyme').hasClass("on")) {
      var viewPreferences = 1;
    } else {
      var viewPreferences = 0;
    }
    if($('.editUseThirdboxDiv').hasClass('on')) {
      var thirdbox = 1;
    } else {
      var thirdbox = 2;
    }
    // console.log("deckInfoSave called");
    $.ajax({
      type: "POST",
      url: "/edit/deckInfoSave.php",
      data: {
        pDeckid: deck_id,
        pDeckname: deckname,
        pCardCount: cardCount,
        pDeckTermLanguage: deckTermLanguage,
        pDeckDefinitionLanguage: deckDefinitionLanguage,
        pDeckThirdBoxLanguage: deckThirdBoxLanguage,
        pThirdbox: thirdbox,
        pDeckDescription: deckDescription,
        pViewPreferences: viewPreferences
      }
    }).done(function(data) {
      // console.log(data);
      // decksaved = 1;
    });
  }
  // prepares edited card array
  // gets all needed values and stores in holdSaveCardArray
  var holdSaveCardArray = [];
  for(i = 0; i < updateSaveArray.length; ++i) {
    var currentCard_id = updateSaveArray[i],
      rowidClass = ".row_" + currentCard_id,
      text1val = $(rowidClass + " .text1").val(),
      text2val = $(rowidClass + " .text2").val(),
      text3val = $(rowidClass + " .text3").val();
    cardOrder = $(".editMain li.mainLi:visible").index($(rowidClass)) + 1;
    holdSaveCardArray[holdSaveCardArray.length] = {
      "card_id": currentCard_id,
      "text1val": text1val,
      "text2val": text2val,
      "text3val": text3val,
      "cardOrder": cardOrder
    };
  }
  // console.log(print_r(holdSaveCardArray));
  // delete cards start
  // deletes any card with an id in updateDeleteArray
  $.ajax({
    type: "POST",
    url: "/edit/deleteCards.php",
    data: {
      pDeck_id: deck_id,
      pDeleteArray: updateDeleteArray
    }
  }).done(function(msg) {
    // $('.temp').append(msg);
    updateDeleteArray = [];
  });
  // save cards to database
  // loops through each card that had changes made to it
  $.ajax({
    type: "POST",
    url: "/edit/saveCardsArray.php",
    dataType: "JSON",
    data: {
      pDeck_id: deck_id,
      pCardArray: holdSaveCardArray
    }
  }).done(function(data) {
    for(var i = 0; i < data.length; i++) {
      var temp_id = data[i]["temp_id"], // new id
        card_key = data[i]["card_key"], // old id
        currentClassName = 'row_' + temp_id,
        currentClass = '.row_' + temp_id,
        nextClassName = 'row_' + card_key;
      $(currentClass).val(card_key);
      $(currentClass).removeClass(currentClassName).addClass(nextClassName);
    }
  });
  updateSaveArray = [];
  // update order start  // uses li value
  updateOrderArray = [];
  $('.editMain').find(".mainLi").each(function() {
    var temp = $(this).val();
    updateOrderArray[updateOrderArray.length] = temp;
  });
  $.ajax({
    type: "POST",
    url: "/edit/orderCards.php",
    data: {
      pUpdateOrderArray: updateOrderArray
    }
  }).done(function(msg) {
    updateOrder = 0;
  });
  closeLibDLM();
  console.log("closeLibDLM");
  changeSaveStudyButton(1);
} //saveChanges function end

底部的日志将在完成区域中的某些内容后打印。

2 个答案:

答案 0 :(得分:1)

由于您正在进行多次ajax调用,因此您必须稍微更改逻辑。你需要做的是收集一系列的承诺。创建类似的东西。

test :: Double -> Double -> IO Double
test a b = fmap (\u -> if a < u then b + u else 2.0) uniform_float

每次执行ajax调用时,将ajax promise推入该数组并在结尾处返回。然后你的逻辑会稍微改变。

var promises = [];

apply()将获取返回的数组,并将其视为您将每个承诺作为参数给出时。

供参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply

答案 1 :(得分:-1)

$.when用于运行promises。

Promise是一个运行异步操作并具有内部回调的函数。

在您的情况下,您需要修改saveChanges(),使其返回此类函数。

$.ajax就是这样一个功能。

因此,您的代码应该类似于:

function saveChanges() { 

   ...

   return $.ajax( .... )

}

然后你应该做

$.when( function() { return saveChanges() } )
 .done( function() { return showSignInPrompt() } )