((window,undefined){
resolve 和 reject 最终都会调用该函数
var final = (status,value){
if(promise._status !== 'PENDING') ;
所以的执行都是异步调用,保证then是先执行的
setTimeout((){
promise._status = status;
st = promise._status === 'FULFILLED'
queue = promise[st ? '_resolves' : '_rejects'];
while(fn = queue.shift()) {
value = fn.call(promise,value) || value;
}
promise[st ? '_value' : '_reason'] = value;
promise['_resolves'] = promise['_rejects'] = undefined;
});
}
参数是一个函数,内部提供两个函数作为该函数的参数,分别是resolve 和 reject
var Promise = (resolver){
if (!(typeof resolver === 'function' ))
new TypeError('You must pass a resolver function as the first argument to the promise constructor');
如果不是promise实例,就new一个
if(!(this instanceof Promise)) Promise(resolver);
;
promise._value;
promise._reason;
promise._status = 'PENDING';
存储状态
promise._resolves = [];
promise._rejects = [];
//
var resolve = (value) {
由於apply參數是數組
final.apply(promise,['FULFILLED'].concat([value]));
}
var reject = (reason){
final.apply(promise,['REJECTED'].concat([reason]));
}
resolver(resolve,reject);
}
Promise.prototype.then = (onFulfilled,onRejected){
每次返回一个promise,保证是可thenable的
handle(value) {
這一步很關鍵,只有這樣才可以將值傳遞給下一個resolve
value;
判断是不是promise 对象
if (ret && typeof ret ['then'] == 'function') {
ret.then((value) {
resolve(value);
},(reason) {
reject(reason);
});
} else {
resolve(ret);
}
}
errback(reason){
reason = typeof onRejected === 'function' && onRejected(reason) || reason;
reject(reason);
}
if(promise._status === 'PENDING'){
promise._resolves.push(handle);
promise._rejects.push(errback);
}if(promise._status === FULFILLED){ 状态改变后的then操作,立刻执行
callback(promise._value);
} REJECTED){
errback(promise._reason);
}
});
}
Promise.prototype.catch = (onRejected){
.then(undefined,onRejected)
}
Promise.prototype.delay = (ms,1)">this.then((ori){
return Promise.delay(ms,value || ori);
})
}
Promise.delay = (){
resolve(value);
console.log('1');
},ms);
})
}
Promise.resolve = (arg){
= len
这里与race中的函数相比,多了一层嵌套,要传入index
resolver(index) {
(value) {
resolveAll(index,value);
};
}
value;
){
resolve(result)
}
}
) {
promises[i].then(resolver(i),rejecter);
}
});
}
Promise.race = Promise;
})(window);