本文的代碼是在下面這篇文章的基礎(chǔ)進(jìn)行的修改,首先感謝原作者的分享~
Promise實(shí)現(xiàn)原理(附源碼) - 簡(jiǎn)書(shū)
本文代碼修改的主要是:_resolve改為同步執(zhí)行寸五,而then里onFulfilled欣福、onRejected改為異步執(zhí)行闽烙,并捕獲異常;靜態(tài)方法resolve有修改。其他的就是一些無(wú)關(guān)緊要的小修改叶眉。
var executeAsync
if (typeof process=='object' && process.nextTick) {
executeAsync = process.nextTick
} else if (typeof setImmediate=='function') {
executeAsync = setImmediate
} else {
executeAsync = function (fn) {setTimeout(fn, 0)}
}
function callAsync(fn, arg, callback, onError) {
executeAsync(function () {
try {
callback ? callback(fn(arg)) : fn(arg)
} catch (e) {
onError(e)
}
})
}
// 判斷變量否為function
const isFunction = variable => typeof variable === 'function'
// 定義Promise的三種狀態(tài)常量
const PENDING = 'pending'
const FULFILLED = 'fulfilled'
const REJECTED = 'rejected'
class MyPromise {
constructor(handle) {
if (!isFunction(handle)) {
throw new Error('MyPromise must accept a function as a parameter')
}
// 添加狀態(tài)
this._status = PENDING
// 添加狀態(tài)
this._value = null
// 添加成功回調(diào)函數(shù)隊(duì)列
this._fulfilledQueue = []
// 添加失敗回調(diào)函數(shù)隊(duì)列
this._rejectedQueue = []
// 執(zhí)行handle
try {
handle(this._resolve.bind(this), this._reject.bind(this))
} catch (err) {
this._reject(err)
}
}
// 添加resovle時(shí)執(zhí)行的函數(shù)
_resolve(val) {
if (this._status !== PENDING) return
this._status = FULFILLED
// 依次執(zhí)行成功隊(duì)列中的函數(shù),并清空隊(duì)列
const runFulfilled = (value) => {
let cb;
while (cb = this._fulfilledQueue.shift()) {
cb(value)
}
}
// 依次執(zhí)行失敗隊(duì)列中的函數(shù)芹枷,并清空隊(duì)列
const runRejected = (error) => {
let cb
while (cb = this._rejectedQueue.shift()) {
cb(error)
}
}
/* 如果resolve的參數(shù)為Promise對(duì)象衅疙,則必須等待該P(yáng)romise對(duì)象狀態(tài)改變后,
當(dāng)前Promsie的狀態(tài)才會(huì)改變,且狀態(tài)取決于參數(shù)Promsie對(duì)象的狀態(tài)
*/
if (val instanceof MyPromise) {
val.then(value => {
this._value = value
runFulfilled(value)
}, err => {
this._value = err
runRejected(err)
})
} else {
this._value = val
runFulfilled(val)
}
}
// 添加reject時(shí)執(zhí)行的函數(shù)
_reject(err) {
if (this._status !== PENDING) return
// 依次執(zhí)行失敗隊(duì)列中的函數(shù)鸳慈,并清空隊(duì)列
this._status = REJECTED
this._value = err
let cb
while (cb = this._rejectedQueue.shift()) {
cb(err)
}
}
// 添加then方法
then(onFulfilled, onRejected) {
// 返回一個(gè)新的Promise對(duì)象
return new MyPromise((onFulfilledNext, onRejectedNext) => {
// 封裝一個(gè)成功時(shí)執(zhí)行的函數(shù)
let fulfilled = value => {
if (isFunction(onFulfilled)) {
callAsync(onFulfilled, value, res => {
if (res instanceof MyPromise) {
// 如果當(dāng)前回調(diào)函數(shù)返回MyPromise對(duì)象饱溢,必須等待其狀態(tài)改變后在執(zhí)行下一個(gè)回調(diào)
res.then(onFulfilledNext, onRejectedNext)
} else {
// 否則會(huì)將返回結(jié)果直接作為參數(shù),傳入下一個(gè)then的回調(diào)函數(shù)走芋,并立即執(zhí)行下一個(gè)then的回調(diào)函數(shù)
onFulfilledNext(res)
}
}, onRejectedNext)
} else {
try {
onFulfilledNext(value)
} catch (err) {
// 如果函數(shù)執(zhí)行出錯(cuò)绩郎,新的Promise對(duì)象的狀態(tài)為失敗
onRejectedNext(err)
}
}
}
// 封裝一個(gè)失敗時(shí)執(zhí)行的函數(shù)
let rejected = error => {
if (isFunction(onRejected)) {
callAsync(onRejected, error, res => {
if (res instanceof MyPromise) {
// 如果當(dāng)前回調(diào)函數(shù)返回MyPromise對(duì)象,必須等待其狀態(tài)改變后在執(zhí)行下一個(gè)回調(diào)
res.then(onFulfilledNext, onRejectedNext)
} else {
// 否則會(huì)將返回結(jié)果直接作為參數(shù)翁逞,傳入下一個(gè)then的回調(diào)函數(shù)肋杖,并立即執(zhí)行下一個(gè)then的回調(diào)函數(shù)
onFulfilledNext(res)
}
}, onRejectedNext)
} else {
try {
onRejectedNext(error)
} catch (err) {
// 如果函數(shù)執(zhí)行出錯(cuò),新的Promise對(duì)象的狀態(tài)為失敗
onRejectedNext(err)
}
}
}
switch (this._status) {
// 當(dāng)狀態(tài)為pending時(shí)挖函,將then方法回調(diào)函數(shù)加入執(zhí)行隊(duì)列等待執(zhí)行
case PENDING:
this._fulfilledQueue.push(fulfilled)
this._rejectedQueue.push(rejected)
break
// 當(dāng)狀態(tài)已經(jīng)改變時(shí)状植,立即執(zhí)行對(duì)應(yīng)的回調(diào)函數(shù)
case FULFILLED:
fulfilled(this._value)
break
case REJECTED:
rejected(this._value)
break
}
})
}
// 添加catch方法
catch(onRejected) {
return this.then(null, onRejected)
}
// 添加靜態(tài)resolve方法
static resolve(value) {
// 如果參數(shù)是MyPromise實(shí)例或thenable對(duì)象,直接返回value
return value instanceof MyPromise ||
(value && isFunction(value.then)) ? value :
new MyPromise(resolve => resolve(value))
}
// 添加靜態(tài)reject方法
static reject(value) {
return new MyPromise((resolve, reject) => reject(value))
}
// 添加靜態(tài)all方法
static all(list) {
return new MyPromise((resolve, reject) => {
let values = [], count = list.length
for (let i in list) {
// 數(shù)組參數(shù)如果不是MyPromise實(shí)例,先調(diào)用MyPromise.resolve
this.resolve(list[i]).then(res => {
values[i] = res
// 所有狀態(tài)都變成fulfilled時(shí)返回的MyPromise狀態(tài)就變成fulfilled
--count<1 && resolve(values)
}, reject)
}
})
}
// 添加靜態(tài)race方法
static race(list) {
return new MyPromise((resolve, reject) => {
for (let p of list) {
// 只要有一個(gè)實(shí)例率先改變狀態(tài)浅萧,新的MyPromise的狀態(tài)就跟著改變
this.resolve(p).then(res => {
resolve(res)
}, reject)
}
})
}
finally(cb) {
return this.then(
value => MyPromise.resolve(cb()).then(() => value),
reason => MyPromise.resolve(cb()).then(() => { throw reason })
)
}
}
// 測(cè)試代碼
new MyPromise(resolve => {
console.log(1);
resolve(3);
MyPromise.resolve().then(() => console.log(4)).then(() => console.log(5))
}).then(num => { console.log(num) }).then(() => { console.log(6) });
console.log(2)
// 依次輸出:1 2 4 3 5 6