外观
Promise 实现
通过手写 Promise 可了解其原理、认识其特性。
一个对象或函数只要拥有 then 方法且行为满足 Promise/A+ 规范,那他就是一个 Promise。
Promise 构造函数特性
在实现之前需要先列出原生 Promise 的特点。
- 构造函数只能通过
new来调用。
js
Promise((resolve, reject) => {})
// Uncaught TypeError: Promise constructor cannot be invoked without 'new'- 构造函数只接收一个参数,为执行器函数,该函数执行为同步代码。
js
Promise((resolve, reject) => {
console.log(1)
})
console.log(2)
// 1
// 2- 构造函数若接收到非函数值,则抛
TypeError。
js
new Promise(null)
// Uncaught TypeError: Promise resolver null is not a function- 构造函数内的代码会被
try-catch包裹,同步错误会被捕获并转为rejected。
js
new Promise((resolve, reject) => {
null.name
})
// Promise {<rejected>: TypeError: Cannot read properties of null (reading 'name')
// Uncaught (in promise) TypeError: Cannot read properties of null (reading 'name')- 构造函数内,即执行器函数内的异步错误无法被 promise 捕获,错误将冒泡到全局,所以此时用 promise 的
catch方法无法捕获该错误。
js
const p = new Promise(() => {
setTimeout(() => {
null.name
})
})
p.catch(error => {
console.log('catch error:', error)
})
// Promise {<pending>}
// Uncaught TypeError: Cannot read properties of null (reading 'name')- Promise 状态一旦落定则不可变,多次调用
resolve或reject时会被忽略,但该调用语句之后的代码会执行。
js
new Promise((resolve, reject) => {
reject('no')
resolve('ok')
console.log('end')
})
// end
// Promise {<rejected>: 'no'}- 循环引用检测,
resolve的值如果是当前 promise 本身,则抛TypeError。
js
const p = new Promise((resolve) => {
setTimeout(() => {
resolve(p)
})
})
// Uncaught (in promise) TypeError: Chaining cycle detected for promise #<Promise>Then 方法特性
then 方法是核心,规范里大部分内容都是在描述 then 方法。
- 每个 Promise 实例对象都有
then方法,且then方法总是会返回一个 Promise。
js
const p = new Promise((resolve, reject) => reject())
const p2 = p.then(null, error => console.log(error))
console.log(p2)
// Promise {<fulfilled>}- Promise 实例执行多个
then时,状态落定后,这些then方法的回调将依次执行。
js
const p = new Promise((resolve) => resolve())
p.then(() => console.log(1))
p.then(() => console.log(2))
// 1
// 2then方法的回调是异步执行,即便 promise 已经是解决状态。
js
const p = new Promise((resolve) => resolve())
p.then(() => console.log(2))
console.log(1)
// 1
// 2then的onFulfilled或onRejected方法若返回 Promise,则新 Promise 的状态由该 Promise 决定。
js
const p = new Promise(resolve => resolve())
p.then(() => {
return Promise.reject('no')
})
// Promise {<rejected>: 'no'}
// Uncaught (in promise) no- 若返回的是
thenable对象,则新 Promise 状态由该thenable对象里的then方法决定。
js
const p = new Promise(resolve => resolve())
p.then(() => {
return {
then(onFulfilled, onRejected) {
onRejected('no')
}
}
})
// Promise {<rejected>: 'no'}
// Uncaught (in promise) no- 除了以上两种情况,其他返回值均会被
Promise.resolve包裹后返回,作为兑现值。
js
const p = new Promise(resolve => resolve())
p.then(() => {
return new Error('error')
})
// Promise {<fulfilled>: Error: error }then方法内返回thenable对象时,其then方法会被自动调用,且会接收到onFulfilled和onRejected两个回调函数,当前 promise 的状态取决于then内部是调用onFulfilled还是onRejected,若都不调用,则状态为pending。
js
const p = new Promise(resolve => resolve())
p.then(() => {
return {
then(onFulfilled, onRejected) {
console.log('then 执行')
console.log(onFulfilled, onRejected)
}
}
})
// then 执行
// ƒ () { [native code] } ƒ () { [native code] }
// Promise {<pending>}then方法的onFulfilled会在兑现时被调用,兑现值将作为回调参数,被拒绝时onRejected被调用,拒绝理由将作为参数。
js
const p = new Promise(resolve => resolve('ok'))
const p2 = new Promise((resolve, reject) => reject('no'))
p.then(res => console.log(res))
p2.then(null, error => console.log(error))
// ok
// nothen方法若接收到非函数值,则会值穿透,会将前一个 promise 的值传給下一个then。
js
const p = new Promise(resolve => resolve('ok'))
p.then()
.then(null)
.then(1)
.then({ name: 'Jay'})
.then([1, 2, 3])
.then(res => {
console.log(res)
})
// ok- 循环引用检测,若
then回调中返回当前 promise 本身,则抛TypeError。
js
const p = new Promise(resolve => resolve())
const p2 = p.then(() => {
return p2
});
// Uncaught (in promise) TypeError: Chaining cycle detected for promise #<Promise>实现
js
const PENDING = 'pending'
const FULFILLED = 'fulfilled'
const REJECTED = 'rejected'
class MyPromise {
#state = PENDING
#handles = []
#value
constructor(executor) {
if (!new.target) {
throw new TypeError('Promise constructor cannot be invoked without new')
}
if (typeof executor !== 'function') {
throw new TypeError(`Promise resolver ${executor} is not a function`)
}
const resolve = (value) => {
this.#setState(FULFILLED, value)
}
const reject = (reason) => {
this.#setState(REJECTED, reason)
}
// 捕获的同步错误将作为 rejected
try {
executor(resolve, reject)
} catch (error) {
reject(error)
}
}
// resolve 和 reject 的调用将改变状态、保存值和执行队列中的回调
#setState(state, value) {
if (this.#state !== PENDING) return
this.#state = state
this.#value = value
this.#runTask()
}
// 执行队列中所有回调并清空队列
#runTask() {
runMicrotask(() => {
if (this.#state === PENDING) return
for (let i = 0; i < this.#handles.length; i++) {
const taskCallback = this.#handles[i]
taskCallback()
}
this.#handles.length = 0
})
}
then(onFulfilled, onRejected) {
return new this.constructor((resolve, reject) => {
this.#handles.push(() => {
try {
const callback = this.#state === FULFILLED ? onFulfilled : onRejected
// 值穿透,若传入非函数则直接传递给下一个 then
const result = typeof callback === 'function' ? callback(this.#value) : this.#value
// promise 展开
if (isPromiseLike(result)) {
result.then(resolve, reject)
} else {
resolve(result)
}
// 执行过程中捕获到的错误将作为 rejected
} catch (error) {
reject(error)
}
})
this.#runTask()
})
}
}
// 模拟微任务
const runMicrotask = (fn) => {
if (typeof queueMicrotask === 'function') {
queueMicrotask(fn)
} else if ( // Node 环境
typeof process === 'object' &&
typeof process.nextTick === 'function'
) {
process.nextTick(fn)
} else if (typeof MutationObserver === 'function') {
const text = document.createTextNode('')
const observer = new MutationObserver(fn)
observer.observe(text, { characterData: true })
text.data = '1'
} else {
setTimeout(fn)
}
}
// 判断一个对象是否是 promise
const isPromiseLike = (obj) => {
return obj != null && typeof obj === 'object' && typeof obj.then === 'function'
}