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


边栏推荐
- servlet与JSP期末复习考点梳理 42问42答
- Pat class a 1024 palindromic number
- 2022 Chinese pastry (Advanced) recurrent training question bank and online simulation test
- JMeter takes the result of the previous request as the parameter of the next request
- 2016Analyzing the Behavior of Visual Question Answering Models
- Window 加密壳实现
- Pat grade a 1018 public bike management
- 超级详细,2 万字详解,吃透 ES!
- Web development framework - Express (installation and use, static hosting, routing processing, use of Middleware)
- Topolvm: kubernetes local persistence scheme based on LVM, capacity aware, dynamically create PV, and easily use local disk
猜你喜欢

Flink learning 4:flink technology stack

学习太极创客 — MQTT(六)ESP8266 发布 MQTT 消息

PAT甲级 1025 PAT Ranking

学习太极创客 — MQTT(七)MQTT 主题进阶

PAT甲级 1019 General Palindromic Number

学习太极创客 — MQTT(八)ESP8266订阅MQTT主题
![455. distribute biscuits [distribution questions]](/img/51/c7544d0eaa121cd461ffa678079473.jpg)
455. distribute biscuits [distribution questions]

TechSmith Camtasia最新2022版详细功能讲解下载

2021:Zero-shot Visual Question Answering using Knowledge Graphs使用知识图的零次视觉问答

JMeter distributed pressure measurement
随机推荐
Super detailed, 20000 word detailed explanation, thoroughly understand es!
Learn from Taiji Maker - mqtt Chapter 2 (I) QoS service quality level
发现一款 JSON 可视化工具神器,太爱了!
Stack overflow vulnerability
Is the money invested in financial products guaranteed? Is there no more?
jmeter将上一个请求的结果作为下一个请求的参数
455. distribute biscuits [distribution questions]
pytorch 23 hook的使用与介绍 及基于hook实现即插即用的DropBlock
PAT甲级 1020 Tree Traversals
苹果手机证书构体知识
超級詳細,2 萬字詳解,吃透 ES!
再探Handler(上)(Handler核心原理最全解析)
Questions and answers of chlor alkali electrolysis process in 2022
测试nohup和&的各自作用
Record the method of reading excel provided by unity and the solution to some pits encountered
使用promise的基本功能【四、Promise源码】
Pat grade a 1025 pat ranking
Human soberness: bottom logic and top cognition
Brief introduction of 228 dropout methods of pytorch and fast implementation of dropblock with 4 lines of code based on dropout
2022中式面点师(高级)复训题库及在线模拟考试