一、手写源码之 Promise

版本一,构造函数

1function MyPromise(fn = () => {}) { 2 // const this = {} 3 this.state = 'pending' 4 this.value = undefined 5 6 const resolve = (value) => { 7 if (this.state === 'pending') { 8 this.state = 'fulfilled' 9 this.value = value 10 } 11 } 12 const reject = (value) => { 13 if (this.state === 'pending') { 14 this.state = 'rejected' 15 this.value = value 16 } 17 } 18 19 this.then = (onFulfilled, onRejected) => { 20 switch (this.state) { 21 case 'fulfilled': 22 onFulfilled(this.value) 23 break 24 case 'rejected': 25 onRejected(this.value) 26 break 27 default: 28 onRejected(this.value); 29 } 30 } 31 32 try { 33 fn(resolve, reject) 34 } catch (e) { 35 reject(e) 36 } 37}

版本二,class类

1class MyPromise { 2 constructor (fn) { 3 this.state = 'pending' 4 this.value = undefined 5 let resolve = value => { 6 if (this.state === 'pending') { 7 this.state = 'fulfilled' 8 this.value = value 9 } 10 } 11 let reject = value => { 12 if (this.state === 'pending') { 13 this.state = 'rejected' 14 this.value = value 15 } 16 } 17 // 自动执行函数 18 try { 19 fn(resolve, reject) 20 } catch (e) { 21 reject(e) 22 } 23 } 24 // then 25 then(onFulfilled, onRejected) { 26 switch (this.state) { 27 case 'fulfilled': 28 onFulfilled(this.value) 29 break 30 case 'rejected': 31 onRejected(this.value) 32 break 33 default: 34 onRejected(this.value); 35 } 36 } 37}

实例化执行

1new MyPromise((resolve, reject) => { 2 console.log('in Promise...') 3 resolve(111) 4}).then((val) => { 5 console.log('resolve', val) 6}, (e) => { 7 console.log('rejected', e) 8})
点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

MySQL部分从库上面因为大量的临时表tmp_table造成慢查询

背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_

皕杰报表之UUID

​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

swap空间的增减方法

(1)增大swap空间去激活swap交换区:swapoff v /dev/vg00/lvswap扩展交换lv:lvextend L 10G /dev/vg00/lvswap重新生成swap交换区:mkswap /dev/vg00/lvswap激活新生成的交换区:swapon v /dev/vg00/lvswap