Paul Ness Paul Ness - 1 month ago 5
Javascript Question

Add multiple callback responses to array

I have this multiple function called

checkForURLS
that calls another two functions that return callbacks, how can I add to the array once both callbacks have returned and then return the array as a callback? I'm working with pure JavaScript.

function checkForURLs(uniqueURL, customURL, callback) {
var errors = [];

checkForUniqueURL(uniqueURL, function(UniqueURLCallback) {
if (UniqueURLCallback===true) {
errors.push("This unique URL is already taken, please try another.");
}
});

if (customURL.length>0) {
checkForCustomURL(customURL, function(customURLCallback) {
if (customURLCallback===true) {
errors.push("This custom URL is already taken, please try another.");
}
});
}

if (errors.length>0) {
return callback(errors);
} else {
return callback(false);
}
}

Answer

You can use Promise constructor new Promise(function), Promise.all() to perform task when checkForUniqueURL and checkForCustomURL callbacks have been called.

function callback(value) {
  return value
}

function checkForUniqueURL(url, callback) {
  return new Promise(function(resolve, reject) {
    setTimeout(function() {
      resolve(callback(true))
    }, Math.random() * 1500)
  })
}

function checkForCustomURL(url, callback) {
  return new Promise(function(resolve, reject) {
    setTimeout(function() {
      resolve(callback(true))
    }, Math.random() * 1500)
  })
}

function checkForURLs(uniqueURL, customURL, callback) {
  var errors = [];

  return Promise.all([
    new Promise(function(resolve, reject) {
      checkForUniqueURL(uniqueURL, function(UniqueURLCallback) {
        if (UniqueURLCallback === true) {
          errors.push("This unique URL is already taken, please try another.");
          resolve()
        }
      })
    })
  , new Promise(function(resolve, reject) {
      if (customURL.length > 0) {
        checkForCustomURL(customURL, function(customURLCallback) {
          if (customURLCallback === true) {
            errors.push("This custom URL is already taken, please try another.");
            resolve()
          }
        });
      }
    })
  ])
  .then(function() {
    if (errors.length > 0) {
        return Promise.resolve(callback(errors));
    } else {
        return Promise.reject(callback(false));
    }
  })
}

checkForURLs("abc", "def", callback)
  .then(function(errs) {
    console.log(errs);
  })
  .catch(function(err) {
    console.log(err)
  })

Comments