您好,登錄后才能下訂單哦!
今天就跟大家聊聊有關(guān)如何實(shí)現(xiàn)一個(gè)簡單的Promise,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。
一個(gè)簡單的 Promise
的粗糙實(shí)現(xiàn),關(guān)鍵點(diǎn)在于
pending
時(shí),
thenable
函數(shù)由一個(gè)隊(duì)列維護(hù)resolved(fulfilled)
時(shí),隊(duì)列中所有
thenable
函數(shù)執(zhí)行resolved
時(shí),
thenable
函數(shù)直接執(zhí)行rejected
狀態(tài)同理
class Prom {
static resolve (value) {
if (value && value.then) {
return value
}
return new Prom(resolve => resolve(value))
}
constructor (fn) {
this.value = undefined
this.reason = undefined
this.status = 'PENDING'
// 維護(hù)一個(gè) resolve/pending 的函數(shù)隊(duì)列
this.resolveFns = []
this.rejectFns = []
const resolve = (value) => {
// 注意此處的 setTimeout
setTimeout(() => {
this.status = 'RESOLVED'
this.value = value
this.resolveFns.forEach(({ fn, resolve: res, reject: rej }) => res(fn(value)))
})
}
const reject = (e) => {
setTimeout(() => {
this.status = 'REJECTED'
this.reason = e
this.rejectFns.forEach(({ fn, resolve: res, reject: rej }) => rej(fn(e)))
})
}
fn(resolve, reject)
}
then (fn) {
if (this.status === 'RESOLVED') {
const result = fn(this.value)
// 需要返回一個(gè) Promise
// 如果狀態(tài)為 resolved,直接執(zhí)行
return Prom.resolve(result)
}
if (this.status === 'PENDING') {
// 也是返回一個(gè) Promise
return new Prom((resolve, reject) => {
// 推進(jìn)隊(duì)列中,resolved 后統(tǒng)一執(zhí)行
this.resolveFns.push({ fn, resolve, reject })
})
}
}
catch (fn) {
if (this.status === 'REJECTED') {
const result = fn(this.value)
return Prom.resolve(result)
}
if (this.status === 'PENDING') {
return new Prom((resolve, reject) => {
this.rejectFns.push({ fn, resolve, reject })
})
}
}
}
Prom.resolve(10).then(o => o * 10).then(o => o + 10).then(o => {
console.log(o)
})
return new Prom((resolve, reject) => reject('Error')).catch(e => {
console.log('Error', e)
})
看完上述內(nèi)容,你們對(duì)如何實(shí)現(xiàn)一個(gè)簡單的Promise有進(jìn)一步的了解嗎?如果還想了解更多知識(shí)或者相關(guān)內(nèi)容,請(qǐng)關(guān)注億速云行業(yè)資訊頻道,感謝大家的支持。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。