当前位置:网站首页>Promise [II. Promise source code] [detailed code comments / complete test cases]
Promise [II. Promise source code] [detailed code comments / complete test cases]
2022-06-27 03:25:00 【Yiyao Bingo】
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
- Function object : resolve,reject,all,race Method
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
function Promise(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
Promise.prototype.then = function(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
Promise.prototype.catch = function(onRejected) {
return this.then(undefined, onRejected);
}
// add to resolve Method
Promise.resolve = function(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
Promise.reject = function(reason) {
return new Promise((resolve, reject) => {
reject(reason);
})
}
// add to all Method
Promise.all = function(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
Promise.race = function(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 :
边栏推荐
- Uni app's uparse rich text parsing perfectly parses rich text!
- TopoLVM: 基于LVM的Kubernetes本地持久化方案,容量感知,动态创建PV,轻松使用本地磁盘
- Mmdetection uses yolox to train its own coco data set
- Pat class a 1024 palindromic number
- Questions and answers of chlor alkali electrolysis process in 2022
- 平均风向风速计算(单位矢量法)
- Learn Tai Chi maker mqtt (IX) esp8266 subscribe to and publish mqtt messages at the same time
- mmdetection 用yolox训练自己的coco数据集
- Flink Learning 2: Application Scenarios
- JMeter takes the result of the previous request as the parameter of the next request
猜你喜欢
学习太极创客 — MQTT(七)MQTT 主题进阶
2021:Zero-shot Visual Question Answering using Knowledge Graphs使用知识图的零次视觉问答
Enterprise digital transformation: informatization and digitalization
2020:MUTANT: A Training Paradigm for Out-of-Distribution Generalizationin Visual Question Answering
发现一款 JSON 可视化工具神器,太爱了!
Learn Tai Chi Maker - mqtt (VIII) esp8266 subscribe to mqtt topic
2021:Greedy Gradient Ensemble for Robust Visual Question Answering
mmdetection ValueError: need at least one array to concatenate解决方案
Mmdetection uses yolox to train its own coco data set
Uni-app 之uParse 富文本解析 完美解析富文本!
随机推荐
2021:AdaVQA: Overcoming Language Priors with Adapted Margin Cosine Loss∗自适应的边缘余弦损失解决语言先验
Pat grade a 1023 have fun with numbers
2019LXMERT:Learning Cross-Modality Encoder Representations from Transformers
Docker deploy redis cluster
元透实盘周记20220627
Flink學習2:應用場景
2019LXMERT:Learning Cross-Modality Encoder Representations from Transformers
2022 Chinese pastry (Advanced) recurrent training question bank and online simulation test
使用promise的基本功能【四、Promise源码】
Introduction to stm32
2021:Check it again:Progressive Visual Question Answering via Visual Entailment通过视觉暗示进行渐进式视觉问答
剑指Offer || :栈与队列(简单)
ESP8266
NestJS环境变量配置,解决如何在拦截器(interceptor)注入服务(service)的问题
流沙画模拟器源码
Pat grade a 1020 tree Traversals
Anaconda3 is missing a large number of files during and after installation, and there are no scripts and other directories
Pat class a 1024 palindromic number
Solve the problem of error reporting in cherry pick submission
Flink Learning 2: Application Scenarios