当前位置:网站首页>手写promise与async await
手写promise与async await
2022-07-05 14:32:00 【原谅我不够洒脱】
promise
先看看promise实现的效果
const Pro = new Promise((resolve,reject) => {
setTimeout(() => {
resolve(123)
}, 5000)
})
Pro.then((res) => {
console.log(res,'----')
})
// 运行代码5秒后控制台打印 123 "----"
自己实现
const PromiseFater = function(callBack) {
this.callBack = callBack
this.then = (back) => {
this.callBack(back)
}
}
const p = new PromiseFater((resolve, reject) => {
console.log(1)
setTimeout(() => {
resolve(123)
}, 5000)
})
p.then((res) => {
console.log(res, '---')
})
// 运行代码5秒后控制台打印 123 "---"
上面只是换了个方法阐述了promise的实现原理,
下面我们加上reject
这代码并不支持连续的.then().then(),只是分析了一下.then().catch()如何实现的,不想把代码搞得太多了,这样不方便看
class MyPromise {
constructor (callBack) {
if (typeof callBack !== 'function') {
throw new Error('必须传入一个函数')
}
// 添加状态
this.status = 'PENDING'
this.thenFun = [] // 存放.then传入的back方法
this.catchFun = [] // 存放.catch传入的back方法
try {
callBack(this.resolve, this.reject)
} catch (err) {
this.reject(err)
}
}
reject = (val) => {
this.status = 'fail'
this.catchFun(val)
}
resolve = (val) => {
this.status = 'success'
this.thenFun(val)
}
then = (back) => {
if (typeof back !== 'function') {
throw new Error('then参数必须传入一个函数')
}
this.thenFun = back
return this
}
catch = (back) => {
if (typeof back !== 'function') {
throw new Error('catch参数必须传入一个函数')
}
this.catchFun = back
return this
}
}
const promise = new MyPromise((resolve, reject) => {
setTimeout(() => {
reject('失败测试')
}, 2000);
})
promise
.then((res) => {
console.log(res)
})
.catch((res) => {
console.log(res)
})
// 运行,控制台上打印 失败测试
如果把
const promise = new MyPromise((resolve, reject) => {
setTimeout(() => {
reject('失败测试')
}, 2000);
})
换成
const promise = new MyPromise((resolve, reject) => {
setTimeout(() => {
resolve('成功测试')
}, 2000);
})
// 运行,控制台上打印 成功测试
如果想实现连续的.then().then(),可以将上面的thenFun 改成thenArr来保存每个then传入的方法,通过状态一次调用,但是何必呢,这样不说写着不好看,用async await他不香嘛
边栏推荐
- FR练习题目---综合题
- 注意!软件供应链安全挑战持续升级
- R language uses the multinom function of NNET package to build an unordered multi classification logistic regression model, and uses the coef function to obtain the log odds ratio corresponding to eac
- 直播预告|如何借助自动化工具落地DevOps(文末福利)
- R语言ggplot2可视化:可视化折线图、使用theme函数中的legend.position参数自定义图例的位置
- 网上电子元器件采购商城:打破采购环节信息不对称难题,赋能企业高效协同管理
- R language ggplot2 visual density map: Visual density map by group and custom configuration geom_ The alpha parameter in the density function sets the image transparency (to prevent multiple density c
- 做自媒体视频二次剪辑,怎样剪辑不算侵权
- 世界环境日 | 周大福用心服务推动减碳环保
- 申请代码签名证书时如何选择合适的证书品牌?
猜你喜欢

FR练习题目---简单题

CYCA少儿形体礼仪 宁波市培训成果考核圆满落幕

微帧科技荣获全球云计算大会“云鼎奖”!

World Environment Day | Chow Tai Fook serves wholeheartedly to promote carbon reduction and environmental protection

分享 12 个最常用的正则表达式,能解决你大部分问题

无密码身份验证如何保障用户隐私安全?

【学习笔记】阶段测试1

世界环境日 | 周大福用心服务推动减碳环保

How to protect user privacy without password authentication?

Thymeleaf th:classappend属性追加 th:styleappend样式追加 th:data-自定义属性
随机推荐
Two policemen were shot dead in a "safety accident" in Philadelphia, USA
The simplest way to open more functions without certificates
Implement a blog system -- using template engine technology
Enjoy what you want. Zhichuang future
R语言dplyr包select函数、group_by函数、mutate函数、cumsum函数计算dataframe分组数据中指定数值变量的累加值、并生成累加数据列
R language dplyr package select function, group_ By function, mutate function and cumsum function calculate the cumulative value of the specified numerical variable in the dataframe grouping data and
2022年国内正规的期货公司平台有哪些啊?方正中期怎么样?安全可靠吗?
不相交集
【学习笔记】阶段测试1
在Pytorch中使用Tensorboard可视化训练过程
快消品行业SaaS多租户解决方案,构建全产业链数字化营销竞争力
Don't be unconvinced. Mobile phone function upgrade is strong
ASP.NET大型外卖订餐系统源码 (PC版+手机版+商户版)
软件测试人在深圳有哪些值得去的互联网公司【软件测试人员专供版】
[learning notes] connectivity and circuit of graph
强联通分量
R语言使用原生包(基础导入包、graphics)中的boxplot函数可视化箱图(box plot)
Pointer operation - C language
实现一个博客系统----使用模板引擎技术
Solution of commercial supply chain collaboration platform in household appliance industry: lean supply chain system management, boosting enterprise intelligent manufacturing upgrading