当前位置:网站首页>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
边栏推荐
猜你喜欢

用getchar清理缓冲区(强烈推荐,C语言易错典型)

Five methods to prevent over fitting of neural network

Pyspark learning notes

TypeScript 高级类型
[email protected] ‘] failed with code 1"/>NPM init vite app < project name > error install for[‘ [email protected] ‘] failed with code 1

大厂面试机器学习算法(5)推荐系统算法

Cell sends SMS asynchronously
[email protected]‘] failed with code 1"/>npm init vite-app <project-name> 报错 Install for [‘[email protected]‘] failed with code 1

【系统问题】.NET Framework 3.5 安装错误

cuda10.0配置pytorch1.7.0+monai0.9.0
随机推荐
大厂面试机器学习算法(0):特征工程 | 数据预处理
Markdown常用语法记录
视图集及路由
Flask blueprint
JDBC Learning and simple Encapsulation
C语言中的分支和循环语句归属
【Pyradiomics】提取的影像组学特征值不正常(很多0和1)
js的防抖和节流
General view, serializer
Partial usage of C #
JWT header进行编码过程
py程序可以运行,但打包出的exe运行提示错误:加载“cv2”二进制扩展时检测到递归。请检查OpenCV安装。
Pytorch white from zero uses North pointing
Scattered notes of machine learning: some concepts and notes
Federated primary keys and indexes
After the formula in word in WPS is copied, there is a picture
systemctl-service服务添加环境变量及模板
WebSocket长连接
从零开始的pytorch小白使用指北
JDBC的學習以及簡單封裝