maybePromise.js 2.48 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
/**
 * This file implements jasminewd's peculiar alternatives to Promise.resolve()
 * and Promise.all().  Do not use the code from this file as polyfill for
 * Promise.resolve() or Promise.all().  There are a number of reasons why this
 * implementation will cause unexpected errors in most codebases.
 *
 * Called "maybePromise" because both the parameters and the return values may
 * or may not be promises, and code execution may or may not be synchronous.
 */


/**
 * Determines if a value is a promise.
 *
 * @param {*} val The value to check.
 * @return {boolean} true if val is a promise, false otherwise.
 */
function isPromise(val) {
  return val && (typeof val.then == 'function');
}


/**
 * Runs a callback synchronously against non-promise values and asynchronously
 * against promises.  Similar to ES6's `Promise.resolve` except that it is
 * synchronous when possible and won't wrap the return value.
 *
 * This is not what you normally want.  Normally you want the code to be
 * consistently asynchronous, and you want the result wrapped into a promise.
 * But because of webdriver's control flow, we're better off not introducing any
 * extra layers of promises or asynchronous activity.
 *
 * @param {*} val The value to call the callback with.
 * @param {!Function} callback The callback function
 * @return {*} If val isn't a promise, the return value of the callback is
 *   directly returned.  If val is a promise, a promise (generated by val.then)
 *   resolving to the callback's return value is returned.
 */
var maybePromise = module.exports = function maybePromise(val, callback) {
  if (isPromise(val)) {
    return val.then(callback);
  } else {
    return callback(val);
  }
}

maybePromise.isPromise = isPromise;

/**
 * Like maybePromise() but for an array of values.  Analogous to `Promise.all`.
 *
 * @param {!Array<*>} vals An array of values to call the callback with
 * @param {!Function} callback the callback function
 * @return {*} If nothing in vals is a promise, the return value of the callback
 *   is directly returned.  Otherwise, a promise (generated by the .then
 *   functions in vals) resolving to the callback's return value is returned.
 */
maybePromise.all = function all(vals, callback) {
  var resolved = new Array(vals.length);
  function resolveAt(i) {
    if (i >= vals.length) {
      return callback(resolved);
    } else {
      return maybePromise(vals[i], function(val) {
        resolved[i] = val;
        return resolveAt(i+1);
      });
    }
  }
  return resolveAt(0);
}