之前曾翻譯過(guò)Promises/A+文檔,但當(dāng)時(shí)僅對(duì)文檔文本內(nèi)容有所了解,而實(shí)際的Promise實(shí)現(xiàn)仍一知半解。最近看到工業(yè)聚老師的《100 行代碼實(shí)現(xiàn) Promises/A+ 規(guī)范》 - 知乎,對(duì)Promise的規(guī)范有了新的理解。以下是參照前文的一個(gè)實(shí)現(xiàn),主要是記錄自己對(duì)Promise的理解。參考注釋:
const PENDING = 'pending'
const FULFILLED = 'fulfilled'
const REJECTED = 'rejected'
// 公共方法
const isObject = (obj) => !!(obj && typeof obj === 'object')
const isFunction = (fn) => typeof fn === 'function'
const isPromise = (promise) => promise instanceof Promise
const isThenable = (obj) => (isFunction(obj) || isObject(obj)) && 'then' in obj
// 1.1 一個(gè)thenable是一個(gè)函數(shù)或者對(duì)象,同時(shí)有then方法
const isIterable = (obj) => {
if (obj == null) {
return false
}
return typeof obj[Symbol.iterator] === 'function'
}
class Promise {
constructor(f) {
this.state = PENDING
this.result = null
this.callbacks = []
const onFulfilled = (value) => transition(this, FULFILLED, value)
const onRejected = (reason) => transition(this, REJECTED, reason)
// 是否狀態(tài)已變化 flag
let ignore = false
const resolve = (value) => {
if (ignore) return
ignore = true
resolvePromise(this, value, onFulfilled, onRejected)
}
const reject = (reason) => {
if (ignore) return
ignore = true
onRejected(reason)
}
// 如果執(zhí)行new Promise時(shí)出錯(cuò),則將錯(cuò)誤傳給reject
try {
f(resolve, reject)
} catch (error) {
reject(error)
}
}
then(onFulfilled, onRejected) {
// 2.2.7 必須返回一個(gè)Promise
return new Promise((resolve, reject) => {
const callback = { onFulfilled, onRejected, resolve, reject }
// 判斷注冊(cè)時(shí),當(dāng)前promise的狀態(tài)
if (this.state === PENDING) {
this.callbacks.push(callback)
} else {
// 如果不是pending,則異步執(zhí)行掉它 3.1
setTimeout(() => handleCallback(callback, this.state, this.result), 0)
// handleCallback拿到的resolve,reject都是屬于then方法返回的promise,我們將它記為promise2
}
})
}
// 規(guī)范內(nèi)沒(méi)有的, ES6的部分實(shí)現(xiàn)
catch(onRejected) {
return this.then(null, onRejected)
}
static resolve(value) {
return new Promise((resolve) => resolve(value))
}
static reject(reason) {
return new Promise((_, reject) => reject(reason))
}
static all(promises) {
if (!isIterable(promises)) {
throw new TypeError('params is not iterable')
}
const results = []
let count = 0
let done = false
return new Promise((resolve, reject) => {
for (const p of promises) {
const i = count++ // 同步遍歷所有迭代器內(nèi)容
Promise.resolve(p).then(
(result) => {
if (done) return
results[i] = result
count-- // resolve 就減少一個(gè)count
if (count === 0 ) {
resolve(results)
}
},
(error) => {
if (done) return
done = true
reject(error)
}
)
}
// 如果傳入的迭代器成員為空,則直接返回迭代器本身
if (count === 0) { resolve(promises) }
})
}
static race(promises) {
if (!isIterable(promises)) {
throw new TypeError('params is not iterable')
}
let done = false
return new Promise((resolve, reject) => {
for (const p of promises) {
count++
Promise.resolve(p).then((result) => {
if (done) return
done = true
resolve(result)
}, (error) => {
if (done) return
done = true
reject(error)
})
}
})
}
}
// promise狀態(tài)遷移公共方法
const transition = (promise, state, result) => {
if (promise.state !== PENDING) return
promise.state = state
promise.result = result
// 異步將所有callbacks執(zhí)行掉
setTimeout(() => {
// resolve時(shí),處理掉所有注冊(cè)的任務(wù)
while (callbacks.length) handleCallback(callbacks.shift(), state, result)
}), 0)
}
// 執(zhí)行then方法注冊(cè)onFulfilled或處理錯(cuò)誤
const handleCallback = (callback, state, result) => {
const { onFulfilled, onRejected, resolve, reject } = callback // resolve, reject 是 then返回的Promise注冊(cè)的方法
try {
// isFunction: 2.2.1 不是函數(shù)則忽略
if (state === FULFILLED) {
// 2.2.7
isFunction(onFulfilled) ? resolve(onFulfilled(result)) : resolve(result)
} else if (state === REJECTED) {
isFunction(onRejected) ? resolve(onRejected(result)) : reject(result)
}
} catch (error) {
reject(error)
}
}
// 2.3 Promise Resolution Procedure 提供互通性
// onFulfilled的返回值 x 如果也是一個(gè)符合規(guī)范的 promise對(duì)象(thenable),
const resolvePromise = (promise, x, resolve, reject) => {
// 2.3.1
if (x === promise) {
const reason = new TypeError('Can not fufill promise with itself')
return reject(reason)
}
// 2.3.2
// 當(dāng)resolve一個(gè)x時(shí),需要等待x的狀態(tài)結(jié)束,再resolve promise自身
// 即,檢查resolve的value 是否是promise,如果是,則通過(guò)then方法注冊(cè),將 promise的狀態(tài)遷移注冊(cè)給 x 的then方法,等待x的fulfilled
if (isPromise(x)) {
return x.then(resolve, reject)
}
// 檢查x是否為thenable對(duì)象,如果是,則表示它可以嘗試讓當(dāng)前實(shí)現(xiàn)的Promise處理
// 通過(guò)這種方式接受其他符合A+規(guī)范的的Promise實(shí)現(xiàn)(實(shí)現(xiàn)了then方法的Promise)
if (isThenable(x)) {
try {
const then = x.then
if (isFunction(then)) {
// 當(dāng)x有then方法,表示它是一個(gè)兼容的Promise實(shí)現(xiàn)
// 這里創(chuàng)建一個(gè)新的Promise,將x的then傳入,并且then原來(lái)的resolve
// 執(zhí)行另一個(gè)異步流程,也就是說(shuō)等待x的狀態(tài)最終為fufilled/rejected執(zhí)行原來(lái)的resolve/reject
// 實(shí)現(xiàn)了對(duì)其他Promise實(shí)現(xiàn)的兼容
return new Promise(then.bind(x)).then(resolve, reject)
}
} catch (error) {
return reject(error)
}
}
// 如果都不是,則resolve掉這個(gè)值
resolve(x)
}
除了基本實(shí)現(xiàn),工業(yè)聚老師的文章還提到一些關(guān)于callback style async的內(nèi)容,十分受用,這里就不展開(kāi)來(lái)說(shuō),原文非常精彩,建議去看一下。