当前位置:网站首页>Promise source code class version [III. promise source code] [detailed code comments / complete test cases]
Promise source code class version [III. promise source code] [detailed code comments / complete test cases]
2022-06-27 03:25:00 【Yiyao Bingo】
JS Classes and objects Follow up explanations
Hand rolling Promise That is to finish promise The main function of
- Declaration constructor
- resolve And reject
- throw Throw an exception to change the State
- Promise The object state of can only be modified once
- then Method to execute the callback
- Synchronize the execution of the task callback
- Execution of asynchronous task callback
- Specify multiple callbacks
- Synchronous modification status then Method returns
- Asynchronous modification state then Method returns
- Promise Of API
- Constructors : then,catch
One 、 index.html
Test Manual promise.js
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="./promise.js"></script>
</head>
<body>
<script> let p = new Promise((resolve, reject) => {
resolve('OK'); // reject("error"); // throw "err"; setTimeout(() => {
// resolve('OK'); // reject('err'); // ............................ What should I do if I throw an error .............. // throw "err"; }, 1000); }); console.log(p); // p.then(value => {
// console.log(value); // }, reason => {
// console.warn(reason); // }) const res = p.then(value => {
// alert(value); return 'hello'; // return new Promise((resolve, reject) => {
// resolve("success"); // // reject("error"); // }) // throw "fail"; }, reason => {
alert(reason); }) console.log(res); let res2 = p.catch(reason => {
console.warn(reason); }) console.log(res2); // extraordinary transmission , Value passed p.then(value => {
// console.log(111); // throw ' failed ' }).then(value => {
console.log(222); }).then(value => {
console.log(333); }).catch(reason => {
console.warn(reason); }) // resolve Method test cases const p1 = Promise.resolve('OK'); const p2 = Promise.resolve(new Promise((resolve, reject) => {
reject("errpr"); })); const p3 = Promise.resolve(Promise.resolve('Oh Yeah!')); console.log(p1); // reject The test case const r1 = Promise.reject('Error'); const r2 = Promise.reject(new Promise((resolve, reject) => {
resolve('ok') })) console.log(r1); console.log(r2); // call all Method let a1 = new Promise((resolve, reject) => {
resolve('OK'); }) let a2 = Promise.resolve('Success'); let a3 = Promise.resolve('Oh Yeah'); let result3 = Promise.all([a1, a2, a3]); console.log(result3); // call race Method let ra1 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('OK'); }) }) let ra2 = Promise.reject('Successs'); let ra3 = Promise.resolve('Oh Yeah!') let result4 = Promise.race([ra1, ra2, ra3]); console.log(result4); // then Asynchronous execution of method callback let then1 = new Promise((resolve, reject) => {
resolve('OK'); console.log(111); }) then1.then(value => {
console.log(222); }) console.log(333); </script>
</body>
</html>
Two 、 promise.js【class edition 】
class Promise {
// Construction method
constructor(executor) {
// Add attribute
this.PromiseState = 'pending';
this.PromiseResult = null;
// Life attribute
this.callbacks = [];
const self = this;
// resolve function
function resolve(data) {
// Promise Object state can only be modified once
if (self.PromiseState !== 'pending') return;
// 1. Modify the state of the object (promiseState)
self.PromiseState = 'fulfilled';
// 2. Set the object result value (promiseResult)
self.PromiseResult = data;
// Call the successful callback function
// if (self.callback.onResolved) {
// self.callback.onResolved(data);
// }
setTimeout(() => {
self.callbacks.forEach(item => {
item.onResolved(item);
})
})
}
// reject function
function reject(data) {
if (self.PromiseState !== 'pending') return;
self.PromiseState = 'rejected';
self.PromiseResult = data;
// Call the failed callback function
// if (self.callback.onRejected) {
// self.callback.onRejected(data);
// }
setTimeout(() => {
self.callbacks.forEach(item => {
item.onRejected(data);
})
})
}
try {
// A synchronous invocation 【 Actuator functions 】
executor(resolve, reject);
} catch (e) {
// modify Promise The object status is failed
reject(e);
}
}
// add to then Method
then(onResolved, onRejected) {
const self = this;
// Determine the callback function parameters -> extraordinary transmission
if (typeof onRejected !== 'function') {
onRejected = reason => {
throw reason;
}
}
if (typeof onResolved !== 'function') {
onResolved = value => value;
// value => { return value; }
}
return new Promise((resolve, reject) => {
// Packaging function
function callback(type) {
try {
// Get the execution result of the callback function
let result = type(self.PromiseResult);
// Judge
if (result instanceof Promise) {
// If it is Promise Object of type
result.then(v => {
resolve(v);
}, r => {
reject(r);
})
} else {
// The object status of the result is success
resolve(result);
}
} catch (e) {
reject(e);
}
}
if (this.PromiseState === 'fulfilled') {
setTimeout(() => {
callback(onResolved);
})
}
if (this.PromiseState === 'rejected') {
setTimeout(() => {
callback(onRejected);
})
}
// Judge pending state
if (this.PromiseState === 'pending') {
// Save callback function
this.callbacks.push({
onResolved: function() {
callback(onResolved);
},
onRejected: function() {
callback(onRejected);
}
})
}
})
}
// add to catch Method
catch (onRejected) {
return this.then(undefined, onRejected);
}
// add to resolve Method 【 Belong to category , Not an instance object 】
static resolve(value) {
// return promise object
return new Promise((resolve, reject) => {
if (value instanceof Promise) {
value.then(v => {
resolve(v);
}, r => {
reject(r);
})
} else {
resolve(value);
}
})
}
// add to reject Method
static reject(reason) {
return new Promise((resolve, reject) => {
reject(reason);
})
}
// add to all Method
static all(promises) {
// The return result is promise object
return new Promise((resolve, reject) => {
// Declare variables
let count = 0;
let arr = [];
// Traverse
for (let i = 0; i < promises.length; i++) {
promises[i].then(v => {
count++;
arr[i] = v;
if (count === promises.length) {
// modify state
resolve(arr);
}
}), r => {
reject(r);
}
}
})
}
// add to race Method
static race(promises) {
return new Promise((resolve, reject) => {
for (let i = 0; i < promises.length; i++) {
promises[i].then(v => {
// Modify the status of the returned object to [ success ]
resolve(v);
}, r => {
reject(r);
})
}
})
}
}
3、 ... and 、 Test return results display :

边栏推荐
- Learn Tai Chi Maker - mqtt Chapter 2 (3) reserved messages
- PAT甲级 1018 Public Bike Management
- Servlet and JSP final review examination site sorting 42 questions and 42 answers
- mmdetection 用yolox训练自己的coco数据集
- Learn Tai Chi maker mqtt (IX) esp8266 subscribe to and publish mqtt messages at the same time
- Mmdetection uses yolox to train its own coco data set
- Record the method of reading excel provided by unity and the solution to some pits encountered
- IDEA中好用的插件
- Implementation of window encryption shell
- PAT甲级 1023 Have Fun with Numbers
猜你喜欢

学习太极创客 — MQTT(九)ESP8266 同时订阅和发布 MQTT 消息
![[array] sword finger offer II 012 The sum of left and right subarrays is equal | sword finger offer II 013 Sum of two dimensional submatrix](/img/e4/7bae2a109dcf5e2a8f032e73b89479.png)
[array] sword finger offer II 012 The sum of left and right subarrays is equal | sword finger offer II 013 Sum of two dimensional submatrix

2021:AdaVQA: Overcoming Language Priors with Adapted Margin Cosine Loss∗自适应的边缘余弦损失解决语言先验

Pat grade a 1025 pat ranking

docker部署redis集群

Cs5213 HDMI to VGA (with audio) single turn scheme, cs5213 HDMI to VGA (with audio) IC

Pat grade a 1021 deep root

Flink learning 5: how it works

【数组】剑指 Offer II 012. 左右两边子数组的和相等 | 剑指 Offer II 013. 二维子矩阵的和

ESP8266
随机推荐
PAT甲级 1020 Tree Traversals
2022中式面点师(高级)复训题库及在线模拟考试
QIngScan使用
2020:MUTANT: A Training Paradigm for Out-of-Distribution Generalizationin Visual Question Answering
PAT甲级 1024 Palindromic Number
2022 Chinese pastry (Advanced) recurrent training question bank and online simulation test
2022 operation of simulated examination platform for tea artist (Senior) work license question bank
Calculation of average wind direction and speed (unit vector method)
学习太极创客 — MQTT 第二章(二)ESP8266 QoS 应用
pytorch_grad_cam——pytorch下的模型特征(Class Activation Mapping, CAM)可视化库
Questions and answers of chlor alkali electrolysis process in 2022
Human soberness: bottom logic and top cognition
Is the division of each capability domain of Dama, dcmm and other data management frameworks reasonable? Is there internal logic?
投资理财产品的钱有保障吗?会不会没有了?
1、项目准备与新建
paddlepaddle 20 指数移动平均(ExponentialMovingAverage,EMA)的实现与使用(支持静态图与动态图)
记录unity 自带读取excel的方法和遇到的一些坑的解决办法
Mmdetection valueerror: need at least one array to concatenate solution
我是怎样简化开源系统中的接口的开发的?
resnet152 辣椒病虫害图像识别1.0