這期內(nèi)容當(dāng)中小編將會(huì)給大家?guī)?lái)有關(guān)如何實(shí)現(xiàn)Promise的方法,文章內(nèi)容豐富且以專(zhuān)業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。
成都創(chuàng)新互聯(lián)是專(zhuān)業(yè)的福貢網(wǎng)站建設(shè)公司,福貢接單;提供成都網(wǎng)站設(shè)計(jì)、成都做網(wǎng)站,網(wǎng)頁(yè)設(shè)計(jì),網(wǎng)站設(shè)計(jì),建網(wǎng)站,PHP網(wǎng)站建設(shè)等專(zhuān)業(yè)做網(wǎng)站服務(wù);采用PHP框架,可快速的進(jìn)行福貢網(wǎng)站開(kāi)發(fā)網(wǎng)頁(yè)制作和功能擴(kuò)展;專(zhuān)業(yè)做搜索引擎喜愛(ài)的網(wǎng)站,專(zhuān)業(yè)的做網(wǎng)站團(tuán)隊(duì),希望更多企業(yè)前來(lái)合作!
1、constructor
首先我們都知道Promise 有三個(gè)狀態(tài),為了方便我們把它定義成常量
const PENDING = 'pending'; const FULFILLED = 'fulfilled'; const REJECTED = 'rejected';
接下來(lái)我們來(lái)定義一個(gè)類(lèi)
class MyPromise { constructor(executor) { //控制狀態(tài),使用了一次之后,接下來(lái)的都不被使用 this.state = PENDING; this.value = null; this.reason = null; // 定義resolve函數(shù) const resolve = value => { if (this.state === PENDING) { this.value = value; this.state = FULFILLED; } } // 定義reject函數(shù) const reject = value => { if (this.state === PENDING) { this.reason = value; this.state = REJECTED; } } // executor方法可能會(huì)拋出異常,需要捕獲 try { // 將resolve和reject函數(shù)給使用者 executor(resolve, reject); } catch (error) { // 如果在函數(shù)中拋出異常則將它注入reject中 reject(error); } } }
到這基本比較好理解我簡(jiǎn)單說(shuō)明一下
executor:這是實(shí)例Promise對(duì)象時(shí)在構(gòu)造器中傳入的參數(shù),一般是一個(gè)function(resolve,reject){}
state:`Promise的狀態(tài),一開(kāi)始是默認(rèn)的pendding狀態(tài),每當(dāng)調(diào)用道resolve和reject方法時(shí),就會(huì)改變其值,在后面的then`方法中會(huì)用到
value:resolve回調(diào)成功后,調(diào)用resolve方法里面的參數(shù)值
reason:reject回調(diào)成功后,調(diào)用reject方法里面的參數(shù)值
resolve:聲明resolve方法在構(gòu)造器內(nèi),通過(guò)傳入的executor方法傳入其中,用以給使用者回調(diào)
reject:聲明reject方法在構(gòu)造器內(nèi),通過(guò)傳入的executor方法傳入其中,用以給使用者回調(diào)
2、then
then就是將Promise中的resolve或者reject的結(jié)果拿到,那么我們就能知道這里的then方法需要兩個(gè)參數(shù),成功回調(diào)和失敗回調(diào),上代碼!
then(onFulfilled, onRejected) { if (this.state === FULFILLED) { onFulfilled(this.value) } if (this.state === REJECTED) { onRejected(this.reason) } }
我們來(lái)簡(jiǎn)單的運(yùn)行一下測(cè)試代碼
const mp = new MyPromise((resolve, reject)=> { resolve('******* i love you *******'); }) mp.then((suc)=> { console.log(11111, suc); }, (err)=> { console.log('****** 你不愛(ài)我了*******', err) }) // 11111 '******* i love you *******'
這樣看著好像沒(méi)有問(wèn)題,那么我們來(lái)試試異步函數(shù)呢?
const mp = new MyPromise((resolve, reject)=> { setTimeout(()=> { resolve('******* i love you *******'); }, 0) }) mp.then((suc)=> { console.log(11111, suc); }, (err)=> { console.log('****** 你不愛(ài)我了*******', err) })
我們會(huì)發(fā)現(xiàn)什么也沒(méi)有打印,哪里出問(wèn)題了呢?原來(lái)是由于異步的原因,當(dāng)我們執(zhí)行到then的時(shí)候this. state的值還沒(méi)發(fā)生改變,所以then里面的判斷就失效了。那么我們?cè)撛趺唇鉀Q呢?
這就要說(shuō)回經(jīng)典得callback 了。來(lái)上源碼
// 存放成功回調(diào)的函數(shù) this.onFulfilledCallbacks = []; // 存放失敗回調(diào)的函數(shù) this.onRejectedCallbacks = []; const resolve = value => { if (this.state === PENDING) { this.value = value; this.state = FULFILLED; this.onFulfilledCallbacks.map(fn => fn()); } } const reject = value => { if (this.state === PENDING) { this.value = value; this.reason = REJECTED; this.onRejectedCallbacks.map(fn => fn()); } }
在then里面添加
then(onFulfilled, onRejected) { // ... if(this.state === PENDING) { this.onFulfilledCallbacks.push(()=> { onFulfilled(this.value); }); this.onRejectedCallbacks.push(()=> { onRejected(this.value); }) } }
好了,到這異步的問(wèn)題解決了,我們?cè)賮?lái)執(zhí)行一下剛才的測(cè)試代碼。結(jié)果就出來(lái)了。到這我們還缺什么呢?
鏈?zhǔn)秸{(diào)用
當(dāng)我們不傳參數(shù)時(shí)應(yīng)當(dāng)什么運(yùn)行
這二個(gè)的思路也都很簡(jiǎn)單,鏈?zhǔn)秸{(diào)用也就是說(shuō)我們?cè)俜祷匾粋€(gè)promise的實(shí)例就好了。而不傳參則就是默認(rèn)值的問(wèn)題了。下面來(lái)看源碼
then(onFulfilled, onRejected) { let self = this; let promise2 = null; //解決onFulfilled,onRejected沒(méi)有傳值的問(wèn)題 onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : y => y //因?yàn)殄e(cuò)誤的值要讓后面訪問(wèn)到,所以這里也要跑出個(gè)錯(cuò)誤,不然會(huì)在之后then的resolve中捕獲 onRejected = typeof onRejected === 'function' ? onRejected : err => { throw err; } promise2 = new MyPromise((resolve, reject) => { if (self.state === PENDING) { console.log('then PENDING') self.onFulfilledCallbacks.push(() => { setTimeout(() => { try { let x = onFulfilled(self.value); console.log(333333, x, typeof x); self.resolvePromise(promise2, x, resolve, reject); } catch (reason) { reject(reason); } }, 0) }); self.onRejectedCallbacks.push(() => { setTimeout(() => { try { let x = onRejected(self.reason); self.resolvePromise(promise2, x, resolve, reject); } catch (reason) { reject(reason); } }, 0); }); } if (self.state === FULFILLED) { console.log('then FULFILLED') setTimeout(() => { try { let x = onFulfilled(self.value); self.resolvePromise(promise2, x, resolve, reject); } catch (reason) { reject(reason); } }, 0); } if (self.state === REJECTED) { console.log('then REJECTED') setTimeout(() => { try { let x = onRejected(self.reason); self.resolvePromise(promise2, x, resolve, reject); } catch (reason) { reject(reason); } }) } }); return promise2; }
為什么外面要包一層setTimeout?:因?yàn)镻romise本身是一個(gè)異步方法,屬于微任務(wù)一列,必須得在執(zhí)行棧執(zhí)行完了在去取他的值,所以所有的返回值都得包一層異步setTimeout。
resolvePromise是什么?:這其實(shí)是官方Promise/A+的需求。因?yàn)槟愕膖hen可以返回任何職,當(dāng)然包括Promise對(duì)象,而如果是Promise對(duì)象,我們就需要將他拆解,直到它不是一個(gè)Promise對(duì)象,取其中的值。
3、resolvePromise
我們直接看代碼
resolvePromise(promise2, x, resolve, reject) { let self = this; let called = false; // called 防止多次調(diào)用 //因?yàn)閜romise2是上一個(gè)promise.then后的返回結(jié)果,所以如果相同,會(huì)導(dǎo)致下面的.then會(huì)是同一個(gè)promise2,一直都是,沒(méi)有盡頭 //相當(dāng)于promise.then之后return了自己,因?yàn)閠hen會(huì)等待return后的promise,導(dǎo)致自己等待自己,一直處于等待 if (promise2 === x) { return reject(new TypeError('循環(huán)引用')); } //如果x不是null,是對(duì)象或者方法 if (x !== null && (Object.prototype.toString.call(x) === '[object Object]' || Object.prototype.toString.call(x) === '[object Function]')) { // x是對(duì)象或者函數(shù) try { let then = x.then; if (typeof then === 'function') { then.call(x, (y) => { // 別人的Promise的then方法可能設(shè)置了getter等,使用called防止多次調(diào)用then方法 if (called) return; called = true; // 成功值y有可能還是promise或者是具有then方法等,再次resolvePromise,直到成功值為基本類(lèi)型或者非thenable self.resolvePromise(promise2, y, resolve, reject); }, (reason) => { if (called) return; called = true; reject(reason); }); } else { if (called) return; called = true; resolve(x); } } catch (reason) { if (called) return; called = true; reject(reason); } } else { // x是普通值,直接resolve resolve(x); } }
為什么要在一開(kāi)始判斷promise2和x?:首先在Promise/A+中寫(xiě)了需要判斷這兩者如果相等,需要拋出異常,我就來(lái)解釋一下為什么,如果這兩者相等,我們可以看下下面的例子,第一次p2是p1.then出來(lái)的結(jié)果是個(gè)Promise對(duì)象,這個(gè)Promise對(duì)象在被創(chuàng)建的時(shí)候調(diào)用了resolvePromise(promise2,x,resolve,reject)函數(shù),又因?yàn)閤等于其本身,是個(gè)Promise,就需要then方法遞歸它,直到他不是Promise對(duì)象,但是x(p2)的結(jié)果還在等待,他卻想執(zhí)行自己的then方法,就會(huì)導(dǎo)致等待。
為什么要遞歸去調(diào)用resolvePromise函數(shù)?:相信細(xì)心的人已經(jīng)發(fā)現(xiàn)了,我這里使用了遞歸調(diào)用法,首先這是Promise/A+中要求的,其次是業(yè)務(wù)場(chǎng)景的需求,當(dāng)我們碰到那種Promise的resolve里的Promise的resolve里又包了一個(gè)Promise的話,就需要遞歸取值,直到x不是Promise對(duì)象。
4、catch
//catch方法 catch(onRejected){ return this.then(null,onRejected) }
5、finally
finally方法用于指定不管 Promise 對(duì)象最后狀態(tài)如何,都會(huì)執(zhí)行的操作。該方法是 ES2018 引入標(biāo)準(zhǔn)的。
finally(fn) { return this.then(value => { fn(); return value; }, reason => { fn(); throw reason; }); };
6、resolve/reject
大家一定都看到過(guò)Promise.resolve()、Promise.reject()這兩種用法,它們的作用其實(shí)就是返回一個(gè)Promise對(duì)象,我們來(lái)實(shí)現(xiàn)一下。
static resolve(val) { return new MyPromise((resolve, reject) => { resolve(val) }) } //reject方法 static reject(val) { return new MyPromise((resolve, reject) => { reject(val) }) }
7、all
all方法可以說(shuō)是Promise中很常用的方法了,它的作用就是將一個(gè)數(shù)組的Promise對(duì)象放在其中,當(dāng)全部resolve的時(shí)候就會(huì)執(zhí)行then方法,當(dāng)有一個(gè)reject的時(shí)候就會(huì)執(zhí)行catch,并且他們的結(jié)果也是按著數(shù)組中的順序來(lái)排放的,那么我們來(lái)實(shí)現(xiàn)一下。
static all(promiseArr) { return new MyPromise((resolve, reject) => { let result = []; promiseArr.forEach((promise, index) => { promise.then((value) => { result[index] = value; if (result.length === promiseArr.length) { resolve(result); } }, reject); }); }); }
8、race
race方法雖然不常用,但是在Promise方法中也是一個(gè)能用得上的方法,它的作用是將一個(gè)Promise數(shù)組放入race中,哪個(gè)先執(zhí)行完,race就直接執(zhí)行完,并從then中取值。我們來(lái)實(shí)現(xiàn)一下吧。
static race(promiseArr) { return new MyPromise((resolve, reject) => { promiseArr.forEach(promise => { promise.then((value) => { resolve(value); }, reject); }); }); }
9、deferred
static deferred() { let dfd = {}; dfd.promies = new MyPromise((resolve, reject) => { dfd.resolve = resolve; dfd.rfeject = reject; }); return dfd; };
什么作用呢?看下面代碼你就知道了
let fs = require('fs') let MyPromise = require('./MyPromise') //Promise上的語(yǔ)法糖,為了防止嵌套,方便調(diào)用 //壞處 錯(cuò)誤處理不方便 function read(){ let defer = MyPromise.defer() fs.readFile('./1.txt','utf8',(err,data)=>{ if(err)defer.reject(err) defer.resolve(data) }) return defer.Promise }
10、測(cè)試
const mp1 = MyPromise.resolve(1); const mp2 = MyPromise.resolve(2); const mp3 = MyPromise.resolve(3); const mp4 = MyPromise.reject(4); MyPromise.all([mp1, mp2, mp3]).then(x => { console.log(x); }, (err) => { console.log('err1', err); }) MyPromise.race([mp1, mp4, mp2, mp3]).then(x => { console.log(x); }, (err) => { console.log('err2', err); }) var mp = new MyPromise((resolve, reject) => { console.log(11111); setTimeout(() => { resolve(22222); console.log(3333); }, 1000); }); mp.then(x => { console.log(x); }, (err) => { console.log('err2', err); }) //11111 //[ 1, 2, 3 ] //1 //3333 //22222
上述就是小編為大家分享的如何實(shí)現(xiàn)Promise的方法了,如果剛好有類(lèi)似的疑惑,不妨參照上述分析進(jìn)行理解。如果想知道更多相關(guān)知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。