当前位置:网站首页>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
边栏推荐
- C语言中的流氓goto语句
- Uscd pedestrian anomaly data set user guide | quick download
- Fun code rain, share it online~-
- 【无标题】
- JS, pay attention to passing parameters. If it is a string, you need to add escape characters
- 对NLP中transformer里面decoder的理解
- 高阶函数的应用:手写Promise源码(三)
- 【无标题】
- Matrix vector derivation in machine learning
- 手写Promise.resolve,Promise.reject, Promise.all
猜你喜欢

pycharm如何正确打包ocr且让打包出来的exe尽量小

TypeScript 高级类型

Pywinauto+某应用程序(学习至第9讲)--受阻

Redis database and project framework

Redis数据库和项目框架

Pycharm occupies C disk

Error handling of "listener not started or database service not registered" in Oracle database creation
![[pytho-flask筆記5]藍圖簡單使用](/img/0a/00b259f42e2fa83d4871263cc5f184.png)
[pytho-flask筆記5]藍圖簡單使用

systemctl-service服务添加环境变量及模板

When using cache in sprintboot, the data cannot be loaded
随机推荐
JS, pay attention to passing parameters. If it is a string, you need to add escape characters
【系统问题】.NET Framework 3.5 安装错误
js的防抖和节流
大厂面试机器学习算法(6)时间序列分析
【文献调研】在Pubmed上搜索特定影响因子期刊上的论文
Using pytorch to realize the flower recognition classifier based on VGg 19 pre training model, the accuracy reaches 97%
Transform: translate (-50%, -50%) border problem
js的闭包的理解
Application of higher-order functions: handwritten promise source code (II)
IMG tag settings height and width are invalid
Differences and basic operations of shell/sh/bash
JS event loop
Spark常见面试问题整理
[python flask notes 5] blueprint is easy to use
用getchar清理缓冲区(强烈推荐,C语言易错典型)
知识点回顾
C语言之二分查找法或折半查找法剖析(经典例题,经典解析)
JS higher order function
大厂面试机器学习算法(5)推荐系统算法
Mixed view base class