使用Promise的多个jQuery Ajax调用

时间:2018-10-31 14:23:56

标签: javascript jquery ajax promise

我正在慢慢使用承诺,但现在需要处理多个承诺。这是我的代码的一部分,该代码有一个表单中的两个电子邮件输入,这两个电子邮件输入都生成承诺,并且都必须在提交表单之前进行处理。我该如何处理这种情况?

// checks form submission
$('#ml_doaction').on('click', function(e) {
  e.preventDefault();
  var isOK = true;
  $('form#volreg :input').each(function(){
    var id = this.id;
    switch(id)
    {
      case 'email_one':
      case 'email_two':
        checkEmailStatus(id, true).then(function(data) {
          if(isOK && data !== false) {
            // submit form
            $('form#volreg').submit();
          }
        });
      break;

      // etc ....
      //other validation functions that set isOK appropriately
    }
  });
});

$('#email').blur(function(){checkEmailStatus('email_one')});
$('#contact_email').blur(function(){checkEmailStatus('email_two')});
function checkEmailStatus(id)
{
  var emailVal = $('#' + id).val();
  var dfd = $.Deferred();

  $.ajax({
    type: 'POST',               
    data:{'checkEmailStatus':emailVal, 'checkList': 'General'},
    url:'/php/ajax/validation-ajax.php',
    success:function(response){
      if(response == 'notinlist') {
        dfd.resolve(false);
      }
      else if(response == 'yesinlist') {  
        dfd.resolve(true);
      }
    },
  });
  return dfd.promise();
}

1 个答案:

答案 0 :(得分:1)

您使用Promise.all函数

 var promises = [];
 $('form#volreg :input').each(function(){
    var id = this.id;
    switch(id)
    {
      case 'email_one':
      case 'email_two':
        promises.push(checkEmailStatus(id, true));
      break;

      // etc ....
      //other validation functions that set isOK appropriately
    }
  });

    Promise.all(promises).then(function(values) {
      var isData = true;
       $.each(values,function(v) {
           if(v == false) {isData = false;
           break;}
        })
       if(isOK && isData !== false) {
            // submit form
            $('form#volreg').submit();
          }
    });