maybePromise.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /**
  2. * This file implements jasminewd's peculiar alternatives to Promise.resolve()
  3. * and Promise.all(). Do not use the code from this file as polyfill for
  4. * Promise.resolve() or Promise.all(). There are a number of reasons why this
  5. * implementation will cause unexpected errors in most codebases.
  6. *
  7. * Called "maybePromise" because both the parameters and the return values may
  8. * or may not be promises, and code execution may or may not be synchronous.
  9. */
  10. /**
  11. * Determines if a value is a promise.
  12. *
  13. * @param {*} val The value to check.
  14. * @return {boolean} true if val is a promise, false otherwise.
  15. */
  16. function isPromise(val) {
  17. return val && (typeof val.then == 'function');
  18. }
  19. /**
  20. * Runs a callback synchronously against non-promise values and asynchronously
  21. * against promises. Similar to ES6's `Promise.resolve` except that it is
  22. * synchronous when possible and won't wrap the return value.
  23. *
  24. * This is not what you normally want. Normally you want the code to be
  25. * consistently asynchronous, and you want the result wrapped into a promise.
  26. * But because of webdriver's control flow, we're better off not introducing any
  27. * extra layers of promises or asynchronous activity.
  28. *
  29. * @param {*} val The value to call the callback with.
  30. * @param {!Function} callback The callback function
  31. * @return {*} If val isn't a promise, the return value of the callback is
  32. * directly returned. If val is a promise, a promise (generated by val.then)
  33. * resolving to the callback's return value is returned.
  34. */
  35. var maybePromise = module.exports = function maybePromise(val, callback) {
  36. if (isPromise(val)) {
  37. return val.then(callback);
  38. } else {
  39. return callback(val);
  40. }
  41. }
  42. maybePromise.isPromise = isPromise;
  43. /**
  44. * Like maybePromise() but for an array of values. Analogous to `Promise.all`.
  45. *
  46. * @param {!Array<*>} vals An array of values to call the callback with
  47. * @param {!Function} callback the callback function
  48. * @return {*} If nothing in vals is a promise, the return value of the callback
  49. * is directly returned. Otherwise, a promise (generated by the .then
  50. * functions in vals) resolving to the callback's return value is returned.
  51. */
  52. maybePromise.all = function all(vals, callback) {
  53. var resolved = new Array(vals.length);
  54. function resolveAt(i) {
  55. if (i >= vals.length) {
  56. return callback(resolved);
  57. } else {
  58. return maybePromise(vals[i], function(val) {
  59. resolved[i] = val;
  60. return resolveAt(i+1);
  61. });
  62. }
  63. }
  64. return resolveAt(0);
  65. }