/*  [Promises/A+ 2.1.3] /*  promise object constructor
337785
function(executor) {
            /*  optionally support non-constructor/plain-function call  */
            if (!(this instanceof Promise)) return new Promise(executor);
            /*  initialize object  */
            this.id = "Thenable/1.0.7";
            this.state = STATE_PENDING;
            /*  initial state  */
            this.fulfillValue = undefined;
            /*  initial value  */
            /*  [Promises/A+ 1.3, 2.1.2.2]  */
            this.rejectReason = undefined;
            /*  initial reason */
            /*  [Promises/A+ 1.5, 2.1.3.2]  */
            this.onFulfilled = [];
            /*  initial handlers  */
            this.onRejected = [];
            /*  initial handlers  */
            /*  support optional executor function  */
            if (typeof executor === "function") executor.call(this, this.fulfill.bind(this), this.reject.bind(this));
        }
35223
function (promises) {
            var count = promises.length;
            if (!count) {
                return null;
            }
            var defer = new Defer();
            for (var i = 0; i < promises.length; i++) {
                /*jshint loopfunc:true*/
                (function (promise, i) {
                    when(promise, function (value) {
                        promises[i] = value;
                        if (--count === 0) {
                            // if all is resolved
                            // then resolve final returned promise with all value
                            defer.resolve(promises);
                        }
                    }, function (r) {
                        // if any one is rejected
                        // then reject final return promise with first reason
                        defer.reject(r);
                    });
                }(promises[i], i));
            }
            return defer.promise;
        }
596452
function createPromise(resolver) {
        return {
            'then': function (onFulfilled, onRejected) {
                return then(resolver, onFulfilled, onRejected);
            },

            'catch': function (onRejected) {
                return then(resolver, null, onRejected);
            }
        };
    }
1149517
function promiseify(method, ctx) {

  // check first
  if (typeof method !== 'function') {
    throw new TypeError(String(method) + ' is not a function');
  }

  return function() {

    // runtime args
    var args = [].slice.call(arguments);

    // runtime this
    ctx = ctx || this;

    return new Promise(function(resolve, reject) {

      args.push(function(err) {
        if (err) {
          return reject(err);
        }
        var arg = [].slice.call(arguments);
        if (arg.length === 2) {
          resolve.call(this, arg[1]);
        } else {
          resolve.call(this, arg.slice(1));
        }
      });

      try {
        method.apply(ctx, args);
      } catch (err) {
        reject(err);
      }
    });
  };
}
544055
function promise (input, value) {
  value.then(val => {
    morph(val, input)
  }, reason => {
    input.emit('error', reason)
  })
}
656879
function (promise, i) {
            var self = this;
            promise.then(
                function () {
                    var args = argsToArray(arguments);
                    args.unshift(i);
                    spreadArgs(self.callback, args, self);
                    promise = i = self = null;
                },
                function () {
                    var args = argsToArray(arguments);
                    args.unshift(i);
                    spreadArgs(self.errback, args, self);
                    promise = i = self = null;
                });
        }
511088
function serial(promises) {
    const results = [];

    return promises
        .reduce((chain, promise) =>
            chain.then(result => {
                results.push(result);
                return promise
            }), Promise.resolve())
        .then(result => {
            results.push(result);
            results.shift();
            return results;
        })
}
335216
@SafeVarargs
    public final PromiseAggregator<V, F> add(Promise<V>... promises) {
        if (promises == null) {
            throw new NullPointerException("promises");
        }
        if (promises.length == 0) {
            return this;
        }
        synchronized (this) {
            if (pendingPromises == null) {
                int size;
                if (promises.length > 1) {
                    size = promises.length;
                } else {
                    size = 2;
                }
                pendingPromises = new LinkedHashSet<Promise<V>>(size);
            }
            for (Promise<V> p : promises) {
                if (p == null) {
                    continue;
                }
                pendingPromises.add(p);
                p.addListener(this);
            }
        }
        return this;
    }
75512
function wrapParsePromise(promise, parsePromise) {
      ['_rejected', '_rejectedCallbacks', '_resolved', '_resolvedCallbacks', '_result', 'reject', 'resolve']
        .forEach(function (prop) {
          promise[prop] = parsePromise[prop];
        });

      ['_continueWith', '_thenRunCallbacks', 'always', 'done', 'fail'].forEach(function (method) {
        promise[method] = wrap(parsePromise[method]);
      });

      ['then', 'catch'].forEach(function (method) {
        var func = promise[method];
        promise[method] = function wrappedAngularPromise() {
          var args = Array.prototype.slice.call(arguments, 0);
          var promise = func.apply(this, args);
          wrapParsePromise(promise, parsePromise);
          return promise;
        };
      });

      return promise;
    }
1219571
function promiseSequence(promiseFactories) {
    return __awaiter(this, void 0, void 0, function* () {
        const ret = [];
        for (const f of promiseFactories) {
            ret.push(yield f());
        }
        return ret;
    });
}
694612
function _resolvePromises (opts, val) {
  opts = opts || {}
  var duplicate = opts.duplicate
  if (is(Array, val)) {
    return Promise.all(duplicate ? concat([], val) : val)
  } else if (duplicate && is(Object, val) && !is(Function, val.then)) {
    return Object.assign({}, val)
  }
  return val
}
449237
function resolvePromise(promise, state, value) {
        var onceWrapper = once();
        if (promise === value) {
            throw new TypeError('Promise resolved with itself');
        }
        if (promise[symbolState] === UNRESOLVED) {
            // should only get value.then once based on promise spec.
            var then = null;
            try {
                if (typeof value === 'object' || typeof value === 'function') {
                    then = value && value.then;
                }
            }
            catch (err) {
                onceWrapper(function () {
                    resolvePromise(promise, false, err);
                })();
                return promise;
            }
            // if (value instanceof ZoneAwarePromise) {
            if (state !== REJECTED && value instanceof ZoneAwarePromise &&
                value.hasOwnProperty(symbolState) && value.hasOwnProperty(symbolValue) &&
                value[symbolState] !== UNRESOLVED) {
                clearRejectedNoCatch(value);
                resolvePromise(promise, value[symbolState], value[symbolValue]);
            }
            else if (state !== REJECTED && typeof then === 'function') {
                try {
                    then.apply(value, [
                        onceWrapper(makeResolver(promise, state)), onceWrapper(makeResolver(promise, false))
                    ]);
                }
                catch (err) {
                    onceWrapper(function () {
                        resolvePromise(promise, false, err);
                    })();
                }
            }
            else {
                promise[symbolState] = state;
                var queue = promise[symbolValue];
                promise[symbolValue] = value;
                // record task information in value when error occurs, so we can
                // do some additional work such as render longStackTrace
                if (state === REJECTED && value instanceof Error) {
                    value[__symbol__('currentTask')] = Zone.currentTask;
                }
                for (var i = 0; i < queue.length;) {
                    scheduleResolveOrReject(promise, queue[i++], queue[i++], queue[i++], queue[i++]);
                }
                if (queue.length == 0 && state == REJECTED) {
                    promise[symbolState] = REJECTED_NO_CATCH;
                    try {
                        throw new Error('Uncaught (in promise): ' + value +
                            (value && value.stack ? '\n' + value.stack : ''));
                    }
                    catch (err) {
                        var error_1 = err;
                        error_1.rejection = value;
                        error_1.promise = promise;
                        error_1.zone = Zone.current;
                        error_1.task = Zone.currentTask;
                        _uncaughtPromiseErrors.push(error_1);
                        api.scheduleMicroTask(); // to make sure that it is running
                    }
                }
            }
        }
        // Resolving an already resolved promise is a noop.
        return promise;
    }
1096790
function promiseOrCallback (callback, executor) {
    var promise = new Promise(executor);

    // no callback: do not attach
    if (typeof callback !== 'function') {
        return promise;
    }

    return promise.then(function (value) {
        setImmediate(function () {
            callback(null, value);
        });
        return value;
    }, function (error) {
        setImmediate(function () {
            callback(error);
        });
        throw error;
    });
}
440042
@Contract(pure = true)
	@NotNull
	public static Promise<Void> all(@NotNull List<? extends Promise<?>> promises) {
		int size = promises.size();
		if (size == 0) return Promise.complete();
		if (size == 1) return promises.get(0).toVoid();
		if (size == 2) return promises.get(0).both(promises.get(1));
		return all(promises.iterator());
	}
469273
function resolve(promise) {
    var method = promise.state === FULFILLED ? 'onFulfilled' : 'onRejected';
    var arg = method === 'onFulfilled' ? promise.value : promise.reason;
    var handler, value;

    nextTick(function() {
      var isPromise;

      while (promise.handlers[0]) {
        handler = promise.handlers.shift();

        try {
          value = handler[method](arg);

          // Handle "thenables" as well as Promises
          isPromise = value instanceof Promise || value && isFunc(value.then);

          if (isPromise) {
            value.then(function(value) { fulfill(handler.promise, value); },
                       function(reason) { reject(handler.promise, reason); });
          } else {
            fulfill(handler.promise, value);
          }
        } catch(err) {
          reject(handler.promise, err);
        }
      }
    });

    return promise;
  }
232090
function promisify() {
    var promiseLike = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;

    if (promiseLike instanceof _es6Promise.Promise) {
        return promiseLike;
    }

    if (typeof promiseLike === "function") {
        return promisify(promiseLike());
    }

    return new _es6Promise.Promise(function (resolve, reject) {
        promiseLike === false ? reject() : resolve(promiseLike);
    });
}
967599
function isPromise(input) {
	return (
		(
			typeof Promise !== 'undefined' &&
			input instanceof Promise
		) ||
		(
			input !== null &&
			typeof input === 'object' &&
			typeof input.then === 'function' &&
			typeof input.catch === 'function'
		)
	);
}