简体   繁体   中英

Multiple jQuery Ajax calls using promises

I'm slowly getting the hang of using promises but now need to handle multiple promises. This is an extract of my code which has two email inputs in a form, both of which generate promises, and both have to be processed before the form can be submitted. How can I deal with this situation?

// 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();
}

You use the Promise.all function

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM