Carl Edwards
Carl Edwards

Reputation: 14434

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. I saw that users here on SO suggested using callbacks to return the value.

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

Upvotes: 2

Views: 81

Answers (1)

Michał Perłakowski
Michał Perłakowski

Reputation: 92471

You should use Promises.

First, you should make your asynchronous functions return a 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:

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

Then you can use submitForm like this:

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

Upvotes: 1

Related Questions