当前位置:网站首页>ES6 feature: Promise (custom encapsulation)
ES6 feature: Promise (custom encapsulation)
2022-07-23 20:46:00 【Lasting bangbangjun】
promise Custom encapsulation
Custom encapsulation resolve and reject
- Promise.js
// Declaration constructor
function Promise(executor){
// Add properties to the object
this.PromiseState = 'pending';
this.PromiseResult = null; // Deposit promise The result of the object
// Used to handle the execution of asynchronous task callback , Array is used to specify multiple callbacks
this.callbacks = [],
// Save the this value
const self = this;
// Definition resolve function
function resolve(data){
// Judge the state , Give Way promise Object state can only be changed once
if(self.PromiseState !== 'pending') return ;
// Modify the state of the object (promiseState)
this.PromiseState = 'fullfilled'; // perhaps resolved
// Set the object result value (promiseResult)
this.PromiseResult = data;
// Call the successful callback function , Use forEach In order that the result of the chain call will not be overwritten
setTimeout(() => {
self.callbacks.forEach(item => {
item.onResolved(data);
})
})
}
// Definition reject function
function reject(data){
// Judge the state , Give Way promise Object state can only be changed once
if(self.PromiseState !== 'rejected') return ;
// Modify the state of the object (promiseState)
this.PromiseState = 'rejected'; // perhaps resolved
// Set the object result value (promiseResult)
this.PromiseResult = data;
// Call the failed callback function
setTimeout(() => {
self.callbacks.forEach(item => {
item.onRejected(data);
})
})
}
// throw Throw exception handling
// A synchronous invocation 【 Actuator functions 】
try{
executor(resolve,reject);
}catch(e){
// modify promise The object status is failed
reject(e);
}
}
// Customize then() Method
Promise.prototype.then = function((onResolved,onRejected) => {
const self = this;
// Determine the callback function parameters ( The principle of realizing exception penetration )
if(typeof onRejected !== 'function'){
onRejected = reason => {
throw reason
}
}
if(typeof onResolved !== 'function'){
onResolved = value => 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 {
resolve(result)
}
}catch(e){
reject(e);
}
}
if(this.PromiseState === 'fullfilled'){
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)
},
})
}
})
})
Promise.prototype.catch = function(onRejected){
return this.then(undefined,onRejected);
}
// Package static 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);
}
}
}
// Package static reject() Method
Promise.reject = function (error){
return new Promise((resolve,reject) => {
reject(error);
})
}
// Package static all() Method
Promise.all = function(promises){
// The return result is promise object
return new Promise((resolve,reject) => {
// Count variables
let count = 0;
// An array of successful results
let arr = [];
for(let i = 0; i<promises.length; i++){
promises[i].then(v => {
// Every promise Execute a successful callback when both are successful
count++;
// Store the results in the array
arr[i] = v;
// If count Results and promises The length of the array is the same
if(count === promises.length){
// take arr Array as a result
resolve(arr);
}
},r=>{
reject(r)
})
}
});
}
// encapsulation race Method
Promise.race = function(promise){
return new Promise((resolve,reject) => {
for(let i = 0; i<promises.length; i++){
promises[i].then(v => {
resolve(v);
},r => {
reject(r);
})
}
})
}
- index.html
<!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>
</head>
<script src="./promise.js"></script>
<body>
<script> let p = new Promise((resolve,reject) => {
resolve('ok'); }); p.then(value => {
console.log(value) },error => {
console.log(error) }) </script>
</body>
</html>
- take promise.js Encapsulation into classes class
class Promise{
constructor(executor){
// Add properties to the object
this.PromiseState = 'pending';
this.PromiseResult = null; // Deposit promise The result of the object
// Used to handle the execution of asynchronous task callback , Array is used to specify multiple callbacks
this.callbacks = [],
// Save the this value
const self = this;
// Definition resolve function
function resolve(data){
// Judge the state , Give Way promise Object state can only be changed once
if(self.PromiseState !== 'pending') return ;
// Modify the state of the object (promiseState)
this.PromiseState = 'fullfilled'; // perhaps resolved
// Set the object result value (promiseResult)
this.PromiseResult = data;
// Call the successful callback function , Use forEach In order that the result of the chain call will not be overwritten
setTimeout(() => {
self.callbacks.forEach(item => {
item.onResolved(data);
})
})
}
// Definition reject function
function reject(data){
// Judge the state , Give Way promise Object state can only be changed once
if(self.PromiseState !== 'rejected') return ;
// Modify the state of the object (promiseState)
this.PromiseState = 'rejected'; // perhaps resolved
// Set the object result value (promiseResult)
this.PromiseResult = data;
// Call the failed callback function
setTimeout(() => {
self.callbacks.forEach(item => {
item.onRejected(data);
})
})
}
// throw Throw exception handling
// A synchronous invocation 【 Actuator functions 】
try{
executor(resolve,reject);
}catch(e){
// modify promise The object status is failed
reject(e);
}
}
then(onResolved,onRejected){
const self = this;
// Determine the callback function parameters ( The principle of realizing exception penetration )
if(typeof onRejected !== 'function'){
onRejected = reason => {
throw reason
}
}
if(typeof onResolved !== 'function'){
onResolved = value => 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 {
resolve(result)
}
}catch(e){
reject(e);
}
}
if(this.PromiseState === 'fullfilled'){
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)
},
})
}
})
}
catch(onRejected){
return this.then(undefined,onRejected);
}
// Package static resolve Method
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);
}
}
}
// Package static reject() Method
static reject(error){
return new Promise((resolve,reject) => {
reject(error);
})
}
// Package static all() Method
static all(promises){
// The return result is promise object
return new Promise((resolve,reject) => {
// Count variables
let count = 0;
// An array of successful results
let arr = [];
for(let i = 0; i<promises.length; i++){
promises[i].then(v => {
// Every promise Execute a successful callback when both are successful
count++;
// Store the results in the array
arr[i] = v;
// If count Results and promises The length of the array is the same
if(count === promises.length){
// take arr Array as a result
resolve(arr);
}
},r=>{
reject(r)
})
}
});
}
// encapsulation race Method
static race (promise){
return new Promise((resolve,reject) => {
for(let i = 0; i<promises.length; i++){
promises[i].then(v => {
resolve(v);
},r => {
reject(r);
})
}
})
}
}
边栏推荐
- jsp+ssm+mysql实现的租车车辆管理系统汽车租赁
- ApplicationContext 介绍
- MySQL(3)
- Lyscripttools extended script module
- Install under win7-vs2012 Net framework work
- Shell command and operation principle
- CDR插件开发之Addon插件002 - 用1分钟编写一个可双击运行的EXE程序
- After the input error of next numerical data type () occurs, it can still be input normally next time
- "Pulse" to the future! Huawei cloud Mrs helps smooth migration to the cloud
- [cloud co creation] what magical features have you encountered when writing SQL every day?
猜你喜欢

Lingo 基本使用

If the order is not paid within 30 minutes, it will be automatically cancelled

LU_ASR01语音模块使用

Quick connect selection recommendation: what are the potential opportunities in the Korean market?

【攻防世界WEB】难度四星12分进阶题:FlatScience

2022.7.11 MySQL job

哈希表、无序集合、映射的原理与实现

速卖通选品推荐:韩国市场有哪些潜力机会商品?

【isprint函数判断字符是否可输出】

Cesium knockout怎么用?
随机推荐
Is the link of Huatai Securities' low commission account opening safe? How to handle low commission
【创建 Birthday Card 应用】
[kernel] platform bus model for driving development and learning
微服务架构 VS 单体服务架构【华为云服务在微服务模式里可以做什么】
Cesium 核心类Viewer-查看器详解
速卖通选品推荐:韩国市场有哪些潜力机会商品?
LU_ Asr01 voice module usage
三层交换机配置MSTP协议详解【华为eNSP实验】
【云享读书会第13期】第五章FFmpeg 查看媒体信息和处理音视频文件的常用方法
NLP领域历史最全必读经典论文分类整理分享(附中文解析)
138-查询案例-涉及知识点:forEach遍历&computed计算属性&v-for循环
[PDD interview] analyze the activity of applications (cameras) in mobile phones
第十一天:续第十天BGP的基本配置
信号的理解
源启数字化:既有模式,还是开源创新?|砺夏行动
【pdd面试】分析手机中的应用(相机)的活跃情况
Day 12: continued day 11 (BGP related knowledge)
13 ways of Excel automation to avoid repeating tasks in Microsoft Excel
Solve the problem that the user clicks quickly and repeats the request within 1 second
Unity解决动画不可用:The AnimationClip ‘XXX‘ used by the Animation component ‘XXX‘ must be marked as Legacy.