简体   繁体   English

使用ajax调用循环函数

[英]Looping through functions with ajax calls

I'm currently looping through a number of functions that validate particular input values.我目前正在遍历许多验证特定输入值的函数。 One in particular requires an ajax call to validate an address.特别是需要一个 ajax 调用来验证地址。 I saw that users here on SO suggested using callbacks to return the value.我看到 SO 上的用户建议使用回调来返回值。

The only problem is, by the time it does retrieve the value, the function had already fired within the loop and returned an undefined value.唯一的问题是,当它确实检索到值时,该函数已经在循环内触发并返回了一个未定义的值。 I've been searching around and wasn't sure what the best solution would be.我一直在四处寻找,但不确定最好的解决方案是什么。 Do I somehow delay the loop?我是否以某种方式延迟了循环? Do I have my function setup right in the first place?我的功能设置是否正确? Need some serious help.需要一些认真的帮助。

var validations = [validateUsername, validatePassword, validateAddress];

function submitForm() { 
  var inputs = validations.map(function(validation) {
    return validation();
  });

  return inputs.every(function(input) {
    return input === true;
  }); // [true, true, undefined]
}

function validateAddress() {
  function addressIsValid(callback) {
    $.ajax({
      type: 'POST',
      url: '/address/validate',
      data: $form.serialize(),
      dataType: 'json',
      success: function(response) {
        return callback(response.Data === 200);
      }
    });
  }

  function callback(response) {
    return response;
  }

  return addressIsValid(callback);
}

You should use Promises .你应该使用Promises

First, you should make your asynchronous functions return a Promise:首先,你应该让你的异步函数返回一个 Promise:

function validateAddress() {
  return new Promise((resolve, reject)=> {
    $.ajax({
      type: 'POST',
      url: '/address/validate',
      data: $form.serialize(),
      dataType: 'json',
      success: response=> {
        response.Data === 200 ? resolve() : reject();
      }
    });
  });
}

Then rewrite your submitForm function like this:然后像这样重写你的submitForm函数:

function submitForm() { 
  var promises = validations.map(validation=> validation());
  return Promise.all(promises)
}

Then you can use submitForm like this:然后你可以像这样使用submitForm

submitForm()
  .then(()=> {
    // form is valid
  }, ()=> {
    // form is invalid
  })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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