Promise 是什么
Promise 是一种规范,在es6以前,浏览器没有内置的promise,不同框架有各自的promise实现,本文中的Promise以es6中的Promise为例。
一个Promise封装了一个操作(异步或同步)的结果和其状态,按我的理解来看,它的出现有以下几点原因,一方面是为了解决回调函数的嵌套问题,如果没有promise 我们可以想象一下,应该如何控制流程,假设有以下场景,执行操作A,如果失败了,执行 操作B,执行操作C,同时B 和 C 失败和成功了也会有对应的处理,这里为了简化,统一使用操作D来处理最终结果,那么最后可能会写出如下的代码
function stepA(arg, onSuccess, onFailure) {
var output = dosomethingA(arg);
var res = output.res;
if (output.success) {
onSuccess(res);
} else {
onFaliure(res);
}
}
function stepB(arg, onSuccess, onFailure) {
var output = dosomethingB(arg);
var res = output.res;
if (output.success) {
onSuccess(res);
} else {
onFaliure(res);
}
}
function stepC(arg, onSuccess, onFailure) {
var output = dosomethingC(arg);
var res = output.res;
if (output.success) {
onSuccess(res);
} else {
onFaliure(res);
}
}
function stepD(arg) {
dosomethingD(arg);
}
stepA('test', function(res) {
stepB(res, stepD, stepD);
}, function(res) {
stepC(res, stepD, stepD);
})
这里如果流程链更长或者将其中的几个step换成是匿名函数的话,就会出现更多的回调嵌套,同时代码会非常的长,根本无法阅读。
还有一个问题是,人们习惯于用线性的思想去思考为题,promise这种链式调用的模式可以将异步代码看起来像同步代码一样执行。
Promsie 的用法
还是刚刚的那个例子,如果用Promise该怎么改写
function executeStep(arg, dosomething) {
return new Promise(function(resolve, reject) {
var result = dosomething(arg);
var res = result.res;
if (result.success) {
resolve(res);
} else {
reject(res);
}
});
}
function dosomethingA(arg) {
// ...
return result;
}
function dosomethingB(arg) {
// ...
return result;
}
function dosomethingC(arg) {
// ...
return result;
}
function dosomethingD(arg) {
// ...
console.log(arg);
}
function wrap(dosomething, result) {
return executeStep(result, dosomething);
}
wrap(dosomethingA, 'test').then(function(result) {
return wrap(dosomethingB, result);
}, function(reason) {
return wrap(dosomethingC, reason);
}).then(dosomethingD, dosomethingD);
根据PromiseA+规范,Promise有3种状态,分别是pending
,rejected
和fullfilled
,其中rejected
和fullfilled
又称为settled
,promise可由pending
转到settled
,处于settled
状态的promise状态不可再变化.
Promise常用API
Promise.prototype.constructor
var promise = new Promise(function(resolve, reject) {
setTimeout(function() {
var res = Math.random();
if (res < 0.5) {
resolve(res);
} else {
reject(res);
}
});
});
其内部实现大体如下
function MyPromise(resolver){
if(typeof resolver !== 'function'){
throw new TypeError(resolver + ' is not a function');
}
if(!(this instanceof MyPromise) return new MyPromise(resolver);
var self = this;
self.status_ = 'PENDING';
self.data_ = undefined;
self.resolveCallBacks = [];
self.rejectCallBacks = [];
function resolve(value){
setTimeout(function(){
if(self.status_ === 'PENDING'){
self.status_ = 'RESOLVED';
self.data_ = value;
for(var i=0; i<self.rejectCallBacks.length; i++){
self.rejectCallBacks[i](value);
}
}
});
}
function reject(reason){
setTimeout(function(){
if(self.status_ === 'PENDING'){
self.status_ = 'REJECTED';
self.data_ = reason;
for(var i=0; i<self.resolveCallBacks.length; i++){
self.resolveCallBacks[i](value);
}
}
});
}
try{
resolver(resolve, reject);
}catch(reason){
reject(reason);
}
}
当通过构造函数创建一个Promise的时候,首先会将其状态设置为PENDING
,同时初始化resolve和reject的回调数组,在这里,resolve
和reject
都是异步调用的,只有当当前Promise状态为PENDING
时,reject
和resolve
内部的代码才会执行, 更改Promise的状态,将结果设置为Promise的值,同时遍历对应的回调数组并执行。
Promise.prototype.then(onFulfilled, onRejected)
这个是Promise中使用频率最高的一个方法了,它会更具Promise的状态选择执行回调或将回掉添加到Promise的回调数组上,大致实现如下
MyPromise.prototype.then = function(onResolved, onRejected) {
onResolved = typeof onResolved === 'function' ? onResolved : function(value){return value};
onRejected = typeof onRejected === 'function' ? onRejected : function(reason){throw reason};
var self = this;
var newPromise;
if(self.status_ === 'RESOLVED'){
newPromise = new MyPromise(function(resolve, reject){
setTimeout(function(){
try{
var x = onResolved(self.data_);
resolvePromise(newPromise, x, resolve, reject);
}catch(reason){
reject(reason);
}
});
});
}else if(self.status_ === 'REJECTED'){
newPromise = new MyPromise(function(resolve, reject){
setTimeout(function(){
try{
var x = onRejected(self.data_);
resolvePromise(newPromise, x, resolve, reject);
}catch(reason){
reject(reason);
}
});
});
}else{
newPromise = new MyPromise(function(resolve, reject){
self.resolveCallBacks.push(function(){
try{
var x = onResolved(self.data_);
resolvePromise(newPromise, x, resolve, reject);
}catch(reason){
rejcet(reason);
}
});
self.rejectCallBacks.push(function(){
try{
var x = onRejected(self.data_);
resolvePromise(newPromise, x, resolve, reject);
}catch(reason){
reject(reason);
}
});
});
}
return newPromise;
};
首先会对传入的回调函数进行检测,如果不是function的话就会使用默认的function(这里的resolvePromise将会在下文讲到),之后判断当前Promise的状态,如果Promise已经决议,则将当前Promise的值传给对应的回调,同时执行resolvePromise
,这些操作会在新创建的Promise中通过异步的方式进行执行,如果当前Promise处于PENDING
状态,则会将回调添加到当前Promise的回调数组中。下面看一下resolvePromise
function resolvePromise(mPromise, x, resolve, reject){
var then;
var thenCalledOrThrow = false;
if(mPromise === x){
return reject(new TypeError('Circle is not expected to exist'));
} // Promises/A+ 2.3.1
if(x instanceof MyPromise){ // 2.3.2
if(x.status_ === 'PENDING'){
x.then(function(value){
resolvePromise(mPromise, value, resolve, reject)
}, reject);
}else{
x.then(resolve, reject);
}
return;
}
if((x != null) && ((typeof x === 'object') || (typeof x === 'function'))){ // 2.3.3
try{
then = x.then; // Maybe then is a getter 2.3.3.1
if(typeof then === 'function'){ // 2.3.3.3
then.call(x, function rs(y){
if(thenCalledOrThrow) return;
thenCalledOrThrow = true;
return resolvePromise(mPromise, y, resolve, reject); // 2.3.3.3.1
}, function rj(r){
if(thenCalledOrThrow) return;
thenCalledOrThrow = true;
return reject(r); // 2.3.3.3.2
});
}else{
return resolve(x); // 2.3.3.4
}
}catch(reason){ // 2.3.3.2
if(thenCalledOrThrow) return;
thenCalledOrThrow = true;
return reject(reason);
}
}else{
return resolve(x); // 2.3.4
}
}
这里注释中的标记代表上文提到的PromiseA+规范中的条目
Promise.prototype.catch(onRejected)
相当于then(null, onRejected)
, 注意的是在Promise里,发生的异常不会输出到控制台,而会被存为Promise的值