1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
| function Promise(executor){ let self = this; self.status = 'pending'; self.value = undefined; self.reason = undefined; self.onResolvedCallbacks = []; self.onRejectedCallbacks = []; function resolve(value){ if(self.status === 'pending'){ self.value = value; self.status = 'resolved'; self.onResolvedCallbacks.forEach(item=>item(self.value)); } } function reject(reason){ if(self.status === 'pending'){ self.reason = reason; self.status = 'rejected'; self.onRejectedCallbacks.forEach(item=>item(self.reason)); } } try{ executor(resolve, reject) }catch(e){ reject(e); } } Promise.prototype.then = function(onFulfilled, onRejected){ onFulfilled = typeof oFulfilled === 'function'?onFulfilled:function(data){return data}; onRejected = typeof onRejected === 'function'?onRejected:function(data){return data}; let self = this; let promise2; if(self.status === 'resolved'){ return promise2 = new Promise(function(resolve, reject){ try{ let x = onFulfilled(self.value); resolvePromise(promise2, x, resolve, reject); }catch(e){ reject(e); } }) } if(self.status === 'rejected'){ return promise2 = new Promise(function(resolve, reject){ try{ let x = onRejected(self.reason); resolvePromise(promise2, x, resolve, reject); }catch(e){ reject(e); } }) } if(self.status === 'pending'){ return promise2 = new Promise(function(resolve, reject){ self.onResolvedCallbacks.push(function(){ let x = onFulfilled(self.value); resolvePromise(promise2, x, resolve, reject); }); self.onRejectedCallbacks.push(function(){ let x = onRejected(self.reason); resolvePromise(promise2, x, resolve, reject); }); }) } } function resolvePromise(promise2, x, resolve, reject){ if(promise2 === x){ throw new TypeError('xxxx'); } if((x !== null) && (typeof x === 'function') || (typeof x === 'object')){ let x = x.then; if(typeof x === 'function'){ then.call(x, fuunction(value){ resolvePromise(promise2, value, resolve, reject); },function(reason){ reject(reason); }) } }else{ resolve(x); } } Promise.prototype.catch = function(func){ return this.then(null, func); } Promise.all = function(promises){ return new Promise(function(resolve, reject){ let result = []; let resolved = function(index){ return function(data){ index++; if(i === promises.length){ resolve(result); } } } for(let i = 0;i< promises.length; i+=1){ promises[i].then(resolved(i)); } }) } module.exports = Promise
|