ES6之Promise学习之路

从开始使用Promise的时候,我认为Promise应该是通过事件+回调来实现。其实,应该也是差不多的,虽说没有看过内部实现,但是我想Promise应该是通过事件+回调,通过容器保存状态来实现的“承诺”,并且“承诺”之后状态变更保存的。Promise有三个状态pending(进行中),Resolved(已完成,又称Fulfilled),Rejected(已失败)。状态的变更只能是从pending-》Resolved或者pending-》Rejected。这种状态变化一旦改变就不在更改。
注意:Reject(err) = throw err;当外部没有做.catch(callback)操作时,
我们可以通过设置process.on(‘unhandledRejection’,function(err,p){}) 来捕获,其中err是错误信息,p是promise对象。

Promise.prototype.then:
then方法是用来指定Resolved状态和Rejected状态所对应的回调函数。
then中的两个参数分别对应Resolved和Rejected。

Promise.prototype.catch
.catch(callback)函数是.then(null, callback)的别名。他们能够捕获到Promise执行函数中Rejected状态和异常(例如throw)。

下面是Promise中catch函数和then函数:

Promise.prototype = {
    constructor: Promise,

    _state: PENDING,
    _then: null,
    _data: undefined,
    _handled: false,

    then: function (onFulfillment, onRejection) {
        var subscriber = {
            owner: this,
            then: new this.constructor(NOOP),
            fulfilled: onFulfillment,
            rejected: onRejection
        };

        if ((onRejection || onFulfillment) && !this._handled) {
            this._handled = true;
            if (this._state === REJECTED && isNode) {
                asyncCall(notifyRejectionHandled, this);
            }
        }

        if (this._state === FULFILLED || this._state === REJECTED) {
            // already resolved, call callback async
            asyncCall(invokeCallback, subscriber);
        } else {
            // subscribe
            this._then.push(subscriber);
        }

        return subscriber.then;
    },

    catch: function (onRejection) {
        return this.then(null, onRejection);
    }
};

Promise.prototype.all
将多个Promise实例包装成一个新的Promise实例。

let p = Promise.all([p1,p2,p3]);

只有当p1,p2,p3都返回Resolved的状态,p才返回Resolved状态,否则p返回Rejected状态。
注意:Promise.all中全部的p1,p2,p3都会被执行,只是p会得到第一个出现异常或者Rejected的信息。

源代码:

Promise.all = function (promises) {
    if (!Array.isArray(promises)) {
        throw new TypeError('You must pass an array to Promise.all().');
    }

    return new Promise(function (resolve, reject) {
        var results = [];
        var remaining = 0;

        function resolver(index) {
            remaining++;
            return function (value) {
                results[index] = value;
                if (!--remaining) {
                    resolve(results);
                }
            };
        }

        for (var i = 0, promise; i < promises.length; i++) {
            promise = promises[i];

            if (promise && typeof promise.then === 'function') {
                promise.then(resolver(i), reject);
            } else {
                results[i] = promise;
            }
        }

        if (!remaining) {
            resolve(results);
        }
    });
};

Promise.prototype.race

与all不同race是返回所有的Promise中第一个发生状态改变之后的信息。

源代码:

Promise.race = function (promises) {
    if (!Array.isArray(promises)) {
        throw new TypeError('You must pass an array to Promise.race().');
    }

    return new Promise(function (resolve, reject) {
        for (var i = 0, promise; i < promises.length; i++) {
            promise = promises[i];

            if (promise && typeof promise.then === 'function') {
                promise.then(resolve, reject);
            } else {
                resolve(promise);
            }
        }
    });
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值