123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160 |
- (function(define) { 'use strict';
- define(function() {
- return function flow(Promise) {
- var resolve = Promise.resolve;
- var reject = Promise.reject;
- var origCatch = Promise.prototype['catch'];
-
- Promise.prototype.done = function(onResult, onError) {
- this._handler.visit(this._handler.receiver, onResult, onError);
- };
-
- Promise.prototype['catch'] = Promise.prototype.otherwise = function(onRejected) {
- if (arguments.length < 2) {
- return origCatch.call(this, onRejected);
- }
- if(typeof onRejected !== 'function') {
- return this.ensure(rejectInvalidPredicate);
- }
- return origCatch.call(this, createCatchFilter(arguments[1], onRejected));
- };
-
- function createCatchFilter(handler, predicate) {
- return function(e) {
- return evaluatePredicate(e, predicate)
- ? handler.call(this, e)
- : reject(e);
- };
- }
-
- Promise.prototype['finally'] = Promise.prototype.ensure = function(handler) {
- if(typeof handler !== 'function') {
- return this;
- }
- return this.then(function(x) {
- return runSideEffect(handler, this, identity, x);
- }, function(e) {
- return runSideEffect(handler, this, reject, e);
- });
- };
- function runSideEffect (handler, thisArg, propagate, value) {
- var result = handler.call(thisArg);
- return maybeThenable(result)
- ? propagateValue(result, propagate, value)
- : propagate(value);
- }
- function propagateValue (result, propagate, x) {
- return resolve(result).then(function () {
- return propagate(x);
- });
- }
-
- Promise.prototype['else'] = Promise.prototype.orElse = function(defaultValue) {
- return this.then(void 0, function() {
- return defaultValue;
- });
- };
-
- Promise.prototype['yield'] = function(value) {
- return this.then(function() {
- return value;
- });
- };
-
- Promise.prototype.tap = function(onFulfilledSideEffect) {
- return this.then(onFulfilledSideEffect)['yield'](this);
- };
- return Promise;
- };
- function rejectInvalidPredicate() {
- throw new TypeError('catch predicate must be a function');
- }
- function evaluatePredicate(e, predicate) {
- return isError(predicate) ? e instanceof predicate : predicate(e);
- }
- function isError(predicate) {
- return predicate === Error
- || (predicate != null && predicate.prototype instanceof Error);
- }
- function maybeThenable(x) {
- return (typeof x === 'object' || typeof x === 'function') && x !== null;
- }
- function identity(x) {
- return x;
- }
- });
- }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
|