//This is javascript
class myPromise{
constructor(executor){
this.state = 'pending';
this.value = null;
this.reason = null;
this.onFullfilledCallbacks = [];
this.onRejectedCallbacks = [];
let resolve = (value) => {
if (this.state === 'pending') {
this.value = value;
this.state = 'fullfilled';
this.onFullfilledCallbacks.forEach(fn => fn());
}
}
let reject = (reason) => {
if (this.state === 'pending') {
this.state = 'rejected';
this.reason = reason;
this.onRejectedCallbacks.forEach(fn => fn());
}
}
try{
executor(resolve,reject)
}catch(e) {
reject(e);
}
}
then(onFullfilled,onRejected) {
// then函數(shù)的作用有兩個(gè)
// 1惫叛、返回一個(gè)promise,后面還可以繼續(xù).then著觉,把回調(diào)記錄在本身promise實(shí)例上面
// 2村生、在promise的executor里面把訂閱函數(shù)記錄在callbacks當(dāng)中,要么同步直接執(zhí)行饼丘,要么異步由resolve來觸發(fā)
onFullfilled = typeof onFullfilled === 'function'?onFullfilled:value => value;
onRejected = typeof onRejected === 'function'?onRejected:err => {throw err};
let promise2 = new myPromise((resolve,reject) => {
if (this.state === 'fullfilled') {
setTimeout(() => {
try{
let x = onFullfilled(this.value);
// 這里是最核心的地方趁桃,需要解析then的fullfill函數(shù)的返回值,當(dāng)前這個(gè)promise需要觸發(fā)自己的resolve函數(shù)肄鸽,才能讓后面的then邏輯執(zhí)行
// 如果是普通值卫病,那么觸發(fā)這里的resolve后面的就可以執(zhí)行了,如果返回的本身也是一個(gè)promise典徘,那就在當(dāng)前的promise后面加一個(gè)then執(zhí)行完之后來resolve當(dāng)前的這個(gè)promise
this.resolvePromise(promise2,x,resolve,reject);
}catch(e) {
reject(e);
}
},0);
}
if (this.state === 'rejected') {
setTimeout(() => {
try{
let x = onRejected(this.reason);
this.resolvePromise(promise2,x,resolve,reject);
}catch(e) {
reject(e);
}
},0);
}
if (this.state === 'pending') {
this.onFullfilledCallbacks.push(() => {
setTimeout(() => {
try{
let x = onFullfilled(this.value);
this.resolvePromise(promise2,x,resolve,reject);
}catch(e) {
reject(e);
}
},0);
})
this.onRejectedCallbacks.push(() => {
setTimeout(() => {
try{
let x = onRejected(this.reason);
this.resolvePromise(promise2,x,resolve,reject);
}catch(e) {
reject(e);
}
},0);
})
}
})
return promise2;
}
resolvePromise(promise2,x,resolve,reject) {
if (promise2 === x) {
reject(new TypeError('circular reference'));
}
let called;
if (x !== null && (typeof x === 'function' || typeof x === 'object')) {
try{
let then = x.then;
if (typeof then === 'function') {
then.call(x,y => {
if (called) return;
called = true;
this.resolvePromise(promise2,y,resolve,reject);
},err => {
if (called) return;
called = true;
reject(err);
})
}else {
if (called) return;
called = true;
resolve(x);
}
}catch(e) {
if (called) return;
called = true;
reject(e);
}
}else {
if (called) return;
called = true;
resolve(x);
}
}
static resolve(value) {
if (value instanceof myPromise) {
return value;
}
return new myPromise((resolve,reject) => {
resolve(value);
})
}
static reject(value) {
if (value instanceof myPromise) {
return value;
}
return new myPromise((resolve,reject) => {
reject(value);
})
}
static all(promiseArray) {
if (!Array.isArray(promiseArray)) {
throw new TypeError('must be an array');
}
let result = [],
i = 0;
return new myPromise((resolve,reject) => {
if (promiseArray.length === 0) {
resolve(result);
}else {
promiseArray.forEach((pro,index) => {
if (pro instanceof myPromise) {
pro.then(value => {
result[index] = value;
i++;
if (i === promiseArray.length) {
resolve(result);
}
},err => {
reject(err);
})
}else {
result[index] = pro;
i++;
if (i === promiseArray.length) {
resolve(result);
}
}
})
}
})
}
static race(promiseArray) {
if (!Array.isArray(promiseArray)) {
throw new TypeError('must be an array');
}
let flag = true;
return new myPromise((resolve,reject) => {
promiseArray.forEach(pro => {
if (pro instanceof myPromise) {
pro.then(res => {
if (flag) {
flag = false;
resolve(res);
}
},err => {
if (flag) {
flag = false;
reject(err);
}
})
}else {
if (flag) {
flag = false;
resolve(pro)
}
}
})
})
}
}
try{
module.exports = myPromise;
}catch(e) {}
實(shí)現(xiàn)的邏輯和說明
上述代碼基本上實(shí)現(xiàn)了所有的Promise/A+規(guī)范蟀苛,實(shí)現(xiàn)了promise的靜態(tài)resolve和reject方法,也實(shí)現(xiàn)了all和race方法烂斋。
1.onFullfilled那里屹逛,給了一個(gè)包裝础废,如果不是方法的話,就稱為一個(gè)參數(shù)為value罕模,return value的方法评腺,實(shí)現(xiàn)了值穿透
2.then里面的方法都是異步的,都要加settimeout
3.resolvePromise放在了對(duì)象里頭淑掌,作為原型方法蒿讥,要控制x的狀態(tài)不可改動(dòng),所以外層加入called抛腕,只要執(zhí)行了該promise的resolve或者reject芋绸,就不能夠再改動(dòng)
4.all方法就是把所有promise對(duì)象執(zhí)行的結(jié)果,給result担敌,然后外層的promise去resolve那個(gè)result即可
5.race方法摔敛,就是全部promise都執(zhí)行then方法,then方法執(zhí)行的時(shí)候全封,成功回調(diào)或者失敗回調(diào)的時(shí)候會(huì)改掉flag马昙,所以只有最先執(zhí)行成功或者失敗回調(diào)的那個(gè)promise的值會(huì)給外層的promise去resolve
6.resolvePromise方法,可以想象為外層的promise對(duì)象刹悴,用自己的resolve和reject一直在找返回值行楞,如果返回值還是promise就繼續(xù)往下遞歸,直到找到那個(gè)普通值土匀,然后給resolve掉子房,不達(dá)目的不罷休
總結(jié)而言,實(shí)現(xiàn)promise還是有一點(diǎn)復(fù)雜的就轧,其中涉及到this指向的細(xì)節(jié)解析then內(nèi)部返回值的問題证杭,代碼大概200行,沒有寫注釋钓丰,留此博客歡迎交流
這里記錄一個(gè)promise的打印順序躯砰,把前面提到的東西都加進(jìn)去
new Promise((resolve, reject) => {
console.log(1);
setTimeout(() => {
console.log(2);
resolve(1)
}, 3000)
}).then(res => {
// 成功的回調(diào)
console.log(3);
return new Promise((resolve1) => {
console.log(4);
setTimeout(() => {
console.log(5);
resolve1()
}, 3000)
}).then(() => {
// 其實(shí)這里的then會(huì)全部跑完才會(huì)resolve外面的
console.log(6)
})
}).then(() => {
console.log(7)
})
上述的打印結(jié)果是1234567每币,如果then里面返回promise的話携丁,會(huì)等promise所有都結(jié)束了之后才會(huì)resolve,這就是resolvePromise做的事情兰怠,因?yàn)樗谧詈笠粋€(gè)promise后面加了一個(gè)then