Competive Races with when.any() some()

briancavalier edited this page Nov 3, 2012 · 1 revision
/**
 * Finds user by email or username.
 *
 * @param {String} query
 */
User.findByEmailOrUsername = function (query) {
  var promises = [];
  promises.push(User.exists({ email: query }));
  promises.push(User.exists({ username: query }));

  return when.any(promises);
}

/**
 * Tests if user exists based on given parameters.
 *
 * returns user's id if user exists and false otherwise.
 * @param {Object} search
 */
User.exists = function (search) {
  var deferred = when.defer();

  User.find(search, function (err, ids) {
    if (err || ids.length == 0) {
      deferred.reject(new Error('user not found'));
    }
    else {
      deferred.resolve(ids[0]);
    }
  });

  return deferred.promise;
}