当前位置:网站首页>Handwriting promise [02] - asynchronous logic implementation
Handwriting promise [02] - asynchronous logic implementation
2022-06-11 06:22:00 【Geek student】
Last handwritten Promise No asynchronous processing , This article implements .
1. Last implemented Promise
const PENDING = 'pending';
const FULFILLED = 'fulfilled';
const REJECTED = 'rejected';
class LyPromise {
constructor(executor) {
executor(this.resolve, this.reject)
}
status = PENDING;
value = undefined;
reason = undefined;
resolve = (value) => {
if (this.status !== PENDING) return;
this.status = FULFILLED;
this.value = value;
}
reject = (reason) => {
if (this.status !== PENDING) return;
this.status = REJECTED;
this.reason = reason;
}
then(successCallback, failCallback) {
if (this.status === FULFILLED) {
successCallback(this.value);
} else if (this.status === REJECTED) {
failCallback(this.reason)
}
}
}
module.exports = LyPromise;
2. Calling LyPromise Add an asynchronous code
const LyPromise = require('./LyPromise')
let promise = new LyPromise((resolve, reject) => {
setTimeout(() => {
resolve(' success ');
// reject(" Failure ");
}, 2000)
})
promise.then(value => {
console.log(value)
}, reason => {
console.log(reason);
})
analysis :
- In order from top to bottom , stay
newOneLyPromiseafter , The callback function in it will execute immediately . - Encountered in the process of execution
setTimeoutAn asynchronous function , Delay 2s Execute the logic inside . promise.thenCallbacks in are immediate , here then Method execution , Judge the current state . But at this timestatusIt's stillPENDING. We areLyPromiseDefinedthenThe method is not rightPENDINGThe judgment of the , Need to be supplemented .
const PENDING = 'pending';
const FULFILLED = 'fulfilled';
const REJECTED = 'rejected';
class LyPromise {
constructor(executor) {
executor(this.resolve, this.reject)
}
status = PENDING;
value = undefined;
reason = undefined;
successCallback = undefined;
failCallback = undefined;
// If there is an asynchronous operation in the actuator , Such as ajax, Timer task time ,then Function status Or waiting ,
// At this point, you do not know whether to execute a success or failure callback , in other words resolve and reject Will be waiting to be executed ,
// So all you need to do is resolve and reject Determine whether there are any success or failure callbacks stored by us , Just do it again
resolve = (value) => {
if (this.status !== PENDING) return;
this.status = FULFILLED;
this.value = value;
// Determine whether a successful callback exists , If there is Call the successful callback
this.successCallback && this.successCallback(this.value);
}
reject = (reason) => {
if (this.status !== PENDING) return;
this.status = REJECTED;
this.reason = reason;
// Determine whether the failed callback exists , If there is Call the failed callback
this.failCallback && this.failCallback(this.reason)
}
then(successCallback, failCallback) {
if (this.status === FULFILLED) {
successCallback(this.value);
} else if (this.status === REJECTED) {
failCallback(this.reason)
} else {
// When the actuator operates asynchronously ,status still pending,
// So at this time, we don't know whether it is a success or a failure callback , So here we need to call back these two
// Store it
this.successCallback = successCallback;
this.failCallback = failCallback;
}
}
}
module.exports = LyPromise;
complete .
边栏推荐
- Make a small game with R language and only basic package
- Shuffleerror:error in shuffle in fetcher solution
- Training and testing of super score model in mmediting
- FPGA interview notes (III) -- implementation of handshake signal synchronization in cross clock domain, arbitrary frequency division, binary conversion, RAM memory, original code inversion and complem
- Using idea to add, delete, modify and query database
- MMEditing中超分模型训练与测试
- go的fmt包使用和字符串的格式化
- Twitter data collection (content, fans, keywords, etc.)
- Notes sur les questions d'entrevue de la FPGA (IV) - - détecteur de séquence, Code gris dans le domaine de l'horloge croisée, opération de ping - pong, réduction de la perte statique et dynamique, err
- FPGA Design -- ping pong operation implementation and Modelsim simulation
猜你喜欢

Deployment of Flink

Compliance management 101: processes, planning and challenges

A piece of code has been refactored six times by the boss, and my mind is broken

Jenkins different styles of project construction

Make a small game with R language and only basic package

Servlet

学好C语言从关键字开始

A multi classification model suitable for discrete value classification -- softmax regression

Verilog realizes binocular camera image data acquisition and Modelsim simulation, and finally matlab performs image display

How to use perforce helix core with CI build server
随机推荐
个人常用软件及浏览器插件分享
How to treat the ethical issues arising from driverless Technology
Servlet
Notes sur les questions d'entrevue de la FPGA (IV) - - détecteur de séquence, Code gris dans le domaine de l'horloge croisée, opération de ping - pong, réduction de la perte statique et dynamique, err
Autojs, read one line, delete one line, and stop scripts other than your own
Eureka cluster setup
Sentinel annotation support - @sentinelresource usage details
Zvuldrill installation and customs clearance tutorial
Sharing of personal common software and browser plug-ins
JIRA software annual summary: release of 12 important functions
Simple knapsack problem
统计某次操作(函数)耗时时长
Goodbye 2021 Hello 2022
Invert an array with for
Ethical discussion on reptile Technology
Sign for this "plug-in" before returning home for the new year
FPGA面试题目笔记(三)——跨时钟域中握手信号同步的实现、任意分频、进制转换、RAM存储器等、原码反码和补码
Chapter 1 of machine learning [series] linear regression model
关于SIoU的原理和代码实现(回顾IoU、GIoU、DIoU、CIoU)
Growth Diary 01