当前位置:网站首页>Application of higher-order functions: handwritten promise source code (4)
Application of higher-order functions: handwritten promise source code (4)
2022-07-23 11:19:00 【Vivqst】
1、 Optimize then Throw exception problem of method
2、 according to then The return value types of the two function parameters received by the method are processed differently
// promise/A+ The specification States promise There are three states , And once the state is changed, it cannot change again
const PENDING = 'Pending'
const FULFILLED = 'Fulfilled'
const REJECTED = 'Rejected'
class Promise {
// Higher order function , The argument to a function is a function , Higher order functions can realize the preset of parameters
// The function in the parameter of the function is the declaration of the function
// executor Is a function that executes immediately , Parameters are preset in constructor in
constructor(executor) {
this.state = PENDING
this.value = undefined // Successful results
this.reason = undefined // The reason for failure
// solve then Problems that can be called multiple times
this.onResolvedCallbacks = []
this.onRejectedCallbacks = []
const resolve = (value) => {
if(this.state === PENDING) {
this.state = FULFILLED
this.value = value
// When the state changes, execute the callback function
this.onResolvedCallbacks.forEach(cb => cb(value))
}
}
const reject = (reason) => {
if(this.state === PENDING) {
this.state = REJECTED
this.reason = reason
// When the state changes, execute the callback function
this.onRejectedCallbacks.forEach(cb => cb(reason))
}
}
// Here is executor Function call . Parameters of the incoming resolve and reject Two functions
try {
executor(resolve, reject)
} catch(err) {
reject(err)
}
}
then(onFulfilledCallback, onRejectedCallback) {
onFulfilledCallback = typeof onFulfilledCallback === 'function' ? onFulfilledCallback : value => value
// Optimization throwing exception
onRejectedCallback = typeof onRejectedCallback === 'function' ? onRejectedCallback : reason => {
throw reason }
// You can chain call , be then It must be a Promise
let promise = new Promise((resolve, reject) => {
if(this.state === FULFILLED) {
// Optimize to catch exceptions
setTimeout(() => {
try {
let res = onFulfilledCallback(this.value)
// according to res Different types of
resolvePromise(promise, res, resolve, reject)
} catch(e) {
reject(e)
}
})
}
if(this.state === REJECTED) {
setTimeout(() => {
try {
let res = onRejectedCallback(this.reason)
resolvePromise(promise, res, resolve, reject)
} catch(e) {
reject(e)
}
})
}
// When executor When an asynchronous task occurs ,then When it comes to execution , The state has not changed , You can put the callback into the callback function array
if(this.state === PENDING) {
this.onResolvedCallbacks.push((value) => {
setTimeout(() => {
try {
let res = onFulfilledCallback(value)
resolvePromise(promise, res, resolve, reject)
} catch(e) {
reject(e)
}
})
})
this.onRejectedCallbacks.push((reason) => {
setTimeout(() => {
try {
let res = onRejectedCallback(reason)
resolvePromise(promise, res, resolve, reject)
} catch(e) {
reject(e)
}
})
})
}
})
return promise
}
}
// According to res The types are treated differently
function resolvePromise(promise, res, resolve, reject) {
if(res === promise) {
return reject(new TypeError(' Dead cycle '))
}
if(res instanceof Promise) {
try {
res.then(x => {
resolvePromise(promise, x, resolve, reject)
// resolve(x)
})
} catch(e) {
reject(e)
}
} else {
resolve(res)
}
}
let p = new Promise((resolve, reject) => {
console.log(2)
setTimeout(() => {
resolve(1)
}, 0)
})
let p2 = new Promise((resolve, reject) => {
resolve(3)
})
let then = p.then(res => {
console.log(res)
return p2
}).then(res => {
console.log(res)
})
console.log(5)
// 2, 5, 1, 3
边栏推荐
- WebSocket长连接
- [部署]presto-server-0.261.tar.gz的集群部署和启动
- Summary of common commands of vim
- D2DEngine食用教程(2)———绘制图像
- 排序、限流
- Sequencing, current limiting
- [Hudi]hudi的编译及hudi&spark和hudi&flink的简单使用
- 【6.28】
- NPM init vite app < project name > error install for[‘ [email protected] ‘] failed with code 1
- [pytho-flask笔记5]蓝图简单使用
猜你喜欢

牛客刷题记录--Mysql
![[Python flask note 5] Blueprint simple à utiliser](/img/0a/00b259f42e2fa83d4871263cc5f184.png)
[Python flask note 5] Blueprint simple à utiliser

Large factory interview machine learning algorithm (0): Feature Engineering | data preprocessing

When using cache in sprintboot, the data cannot be loaded

【uiautomation】键指令大全(以及三种调用方式)+常用鼠标动作+SendKeys+Inspect学习

Flask blueprint
![[pytho-flask筆記5]藍圖簡單使用](/img/0a/00b259f42e2fa83d4871263cc5f184.png)
[pytho-flask筆記5]藍圖簡單使用

cuda10.0配置pytorch1.7.0+monai0.9.0

PyGame realizes the airplane war game
![[flink]flink on yarn之flink-conf最简单配置](/img/de/0ec23f3379148dba27fe77dc51e22f.png)
[flink]flink on yarn之flink-conf最简单配置
随机推荐
pycharm如何正确打包ocr且让打包出来的exe尽量小
混入视图基类
PyGame realizes the airplane war game
First meet flask
Install enterprise pycharm and Anaconda
Celery异步发送短信
【无标题】
[metric]使用Prometheus监控flink1.13org.apache.flink.metrics
Paging and filtering
Pytorch white from zero uses North pointing
Framework introduction Mvt
Spark常见面试问题整理
SQL常见面试题目与答案整理
JDBC learning and simple encapsulation
【无标题】
【6.28】
[untitled]
3. Threads in flask
[pytho-flask筆記5]藍圖簡單使用
【Pyradiomics】提取的影像组学特征值不正常(很多0和1)