从开始使用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);
}
}
});
};