当前位置:网站首页>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 :

边栏推荐
- pytorch_ grad_ Cam -- visual Library of class activation mapping (CAM) under pytorch
- Learn Tai Chi maker mqtt (IX) esp8266 subscribe to and publish mqtt messages at the same time
- 敏捷开发篇--Agile Development-自用
- Pat grade a 1019 general palindromic number
- 流沙画模拟器源码
- 事业观、金钱观与幸福观
- resnet152 辣椒病虫害图像识别1.0
- Yuantou firm offer weekly record 20220627
- PAT甲级 1024 Palindromic Number
- 正则表达式:语法
猜你喜欢

2021:Graphhopper: Multi-Hop Scene Graph Reasoning for Visual Question Answering

Introduction to stm32

JMeter distributed pressure measurement

PAT甲级 1025 PAT Ranking

2020:MUTANT: A Training Paradigm for Out-of-Distribution Generalizationin Visual Question Answering

ESP8266

流沙画模拟器源码

pytorch_ grad_ Cam -- visual Library of class activation mapping (CAM) under pytorch

超级详细,2 万字详解,吃透 ES!

2021:Greedy Gradient Ensemble for Robust Visual Question Answering
随机推荐
2021:Passage Retrieval for Outside-KnowledgeVisual Question Answering通道检索的外部知识视觉问答
pytorch_grad_cam——pytorch下的模型特征(Class Activation Mapping, CAM)可视化库
ESP8266
How does the brain do arithmetic? Both addition and subtraction methods have special neurons, and the symbol text can activate the same group of cell sub journals
Easy to use plug-ins in idea
2016Analyzing the Behavior of Visual Question Answering Models
docker部署redis集群
再探Handler(下)(Handler核心原理最全解析)
Qingscan use
Sword finger offer 𞓜: stack and queue (simple)
Microsoft365 developer request
2022 Chinese pastry (Advanced) recurrent training question bank and online simulation test
Geometric distribution (a discrete distribution)
Learning Tai Chi Maker - mqtt (VII) advanced mqtt theme
苹果手机证书构体知识
Regular expressions: Syntax
Cs5213 HDMI to VGA (with audio) single turn scheme, cs5213 HDMI to VGA (with audio) IC
Mmdetection valueerror: need at least one array to concatenate solution
Record the method of reading excel provided by unity and the solution to some pits encountered
JWT certification process and use cases