今天就跟大家聊聊有关如何实现一个简单的Promise,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。
一个简单的 Promise
的粗糙实现,关键点在于
pending
时,
thenable
函数由一个队列维护resolved(fulfilled)
时,队列中所有
thenable
函数执行resolved
时,
thenable
函数直接执行rejected
状态同理
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' // 维护一个 resolve/pending 的函数队列 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) // 需要返回一个 Promise // 如果状态为 resolved,直接执行 return Prom.resolve(result) } if (this.status === 'PENDING') { // 也是返回一个 Promise return new Prom((resolve, reject) => { // 推进队列中,resolved 后统一执行 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)})
看完上述内容,你们对如何实现一个简单的Promise有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:https://my.oschina.net/u/4592353/blog/4434465