当前位置:网站首页>ES5和SE6来实现一个Promise效果
ES5和SE6来实现一个Promise效果
2022-08-10 13:07:00 【快乐的蜜蜂】
这个是ES5的写法
function myPromise(executor) {
// 定义promise的状态
let self = this;
self.status = "pendding";
self.value = null; // 成功之后 返回数据
self.reason = null; // 失败之后返回原因
// 这个是 发布订阅
self.fulfilledCallbackList = [];
self.rejectCallbackList = [];
// 定义完成时的方法
function resolve(value) {
if (self.status == "pendding") {
self.status = "fulfilled";
self.value = value;
self.fulfilledCallbackList.forEach(item => item(value));
}
}
// 这个是 异常时候的方法
function reject(err) {
if (self.status == "pendding") {
self.status = "rejected";
self.reason = err;
self.rejectCallbackList.forEach(item => item(err));
}
}
// 这个是 立即执行 executor里面的方法
try {
executor && executor(resolve, reject);
} catch (err) {
reject(err.message);
}
}
// 这个是 原型链上面的 then 方法
myPromise.prototype.then = function (onFulfilled, onRejected) {
// 这里 还要 判断一下 传入进来 是不是一个方法
onFulfilled = typeof onFulfilled == 'function' ? onFulfilled : function (data) { resolve(data) };
onRejected = typeof onRejected == 'function' ? onRejected : function (err) { throw err; }
let self = this;
// 这里是 then 里面的回调部分
if (self.status == "fulfilled") {
// 链式调用 就是 直接返回一个 Promise
return new myPromise((resolve, reject) => {
try {
let x = onFulfilled(self.value);
x instanceof myPromise ? x.then(resolve, reject) : resolve(x);
} catch (err) {
reject(err);
}
});
}
// 这个是 失败的状态
if (self.status == "rejected") {
return new myPromise((resolve, reject) => {
try {
let x = onRejected(self.reason);
x instanceof myPromise ? x.then(resolve, reject) : resolve(x);
} catch (err) {
reject(err);
}
});
}
// 这个是 pendding的状态
if (self.status == "pendding") {
return new myPromise((resolve, reject) => {
self.fulfilledCallbackList.push(() => {
let x = onFulfilled(self.value);
x instanceof myPromise ? x.then(resolve, reject) : resolve(x);
});
self.rejectCallbackList.push(() => {
let x = onRejected(self.reason);
x instanceof myPromise ? x.then(resolve, reject) : resolve(x);
});
});
}
}
myPromise.prototype.catch = function(fn) {
this.then(null, fn);
}
const aaa = new myPromise((resolve, reject) => {
console.log(111);
setTimeout(() => {
resolve("2222222222222");
}, 2000);
}).then((res, rej) => {
return new myPromise((re1, rj1)=>{
re1(res + "sdfsdfsdfsdf");
});
}).then((res1, rej1)=>{
console.log(res1);
});
console.log("aaa", aaa);
这个是ES6 Class版本的实现
class MyPromise {
constructor(executor) {
// 这个是 promise的状态机制
this.status = "pendding";
// 这个是 成功的值
this.value = null;
// 这个是 失败的值
this.reason = null;
// 这里是 发布订阅的部分
this.fulfilledCallbacks = [];
this.rejectedCallbacks = [];
// 这个是 立即执行 executor里面的方法
try {
// 这里要绑定 this , 然后下面的 函数 才能 拿到这里的this
executor && executor(this.resolve.bind(this), this.reject.bind(this));
} catch (err) {
this.reject(err.message);
}
}
resolve(data) {
if (this.status == "pendding") {
this.status = "fulfilled";
this.value = data;
// 这个是 发布 订阅里面的函数
this.fulfilledCallbacks.forEach(item => item(data));
}
}
// 这个是 reject 拒绝的方法
reject(err) {
if (this.status == "pendding") {
this.status = "rejected";
this.reason = err;
this.rejectedCallbacks.forEach(item => item(err));
}
}
// 这个是 then 方法
then(onFulfilled, onRejected) {
let self = this;
// 这个是 判断 传进来的是否是 方法
onFulfilled = typeof onFulfilled == 'function' ? onFulfilled : function (data) { self.resolve(data) };
onRejected = typeof onRejected == 'function' ? onRejected : function (err) { throw err };
// 这里是成功的值
if (self.status == "fulfilled") {
// 这里是 链式调用的部分 通过返回 MyPromise 来实现
return new MyPromise((resolve, reject) => {
try {
let x = self.onFulfilled(self.value);
x instanceof MyPromise ? x.then(resolve, reject) : self.resolve(x);
} catch (error) {
reject(error);
}
});
}
// 这里是 失败的时候
if (self.status == "rejected") {
return new MyPromise((resolve, reject) => {
try {
let x = onRejected(self.reason);
x instanceof MyPromise ? x.then(resolve, reject) : self.resolve(x);
} catch (error) {
reject(error);
}
});
}
// 这里是 pendding 加载的时候
if (self.status == "pendding") {
return new MyPromise((resolve, reject) => {
self.fulfilledCallbacks.push(() => {
let x = onFulfilled(self.value);
x instanceof MyPromise ? x.then(resolve, reject) : self.resolve(x);
});
self.rejectedCallbacks.push(() => {
let x = onRejected(self.reason);
x instanceof MyPromise ? x.then(resolve, reject) : self.resolve(x);
});
});
}
}
catch(fn) {
this.then(null, fn);
}
}
const aaa = new MyPromise((resolve, reject) => {
console.log(111);
setTimeout(() => {
resolve("我是输出.");
}, 2000);
}).then((res, rej) => {
return new MyPromise((re1, rj1)=>{
console.log("res", res);
setTimeout(() => {
re1(res + "对,我是后面的输出");
}, 2000);
});
}).then((res1, rej1)=>{
console.log(res1);
});
console.log("aaa", aaa);
边栏推荐
- 用低代码驱动IT现代化
- Reversing words in a string in LeetCode
- Prada, big show?In the yuan in the universe that!
- Import other custom namespaces in C#
- Real-time data warehouse practice of Baidu user product flow and batch integration
- Nanodlp v2.2/v3.0 light curing circuit board, connection method of mechanical switch/photoelectric switch/proximity switch and system state level setting
- C#报错 The ‘xmins‘ attribute is not supported in this context
- jenkins数据迁移和备份
- 递归递推之递归的函数
- How to describe multiple paragraphs with different font settings in Open Office XML format
猜你喜欢

Basic knowledge of switches

Prada, big show?In the yuan in the universe that!

Short read or OOM loading DB. Unrecoverable error, aborting now

【ECCV 2022|百万奖金】PSG大赛:追求“最全面”的场景理解

神了!阿里数据库专家纯手写了这份604页的Oracle+MySQL攻坚指南

Redis上云迁移实践

2022-08-09:以下go语言代码输出什么?A:否,会 panic;B:是,能正确运行;C:不清楚,看投票结果。 package main import ( “fmt“ “syn

机器学习实战(2)——端到端的机器学习项目

Efficient and Robust 2D-to-BEV Representation Learning via Geometry-guided Kernel Transformer 论文笔记

生成树协议STP(Spanning Tree Protocol)
随机推荐
The basic components of Loudi plant cell laboratory construction
C#报错 The ‘xmins‘ attribute is not supported in this context
递归递推之计算组合数
【mysql索引实现原理】
A detailed explanation of implementation api embed
Matrix Keyboard & Calculator Small Project Based on 51 (UcosII)
I would like to ask the big guys, how to solve this error when cdc oracle initializes a 3 million table task running
【量化交易行情不够快?】一文搞定通过Win10 wsl2 +Ubuntu+redis+pickle实现股票行情极速读写
C# error The 'xmins' attribute is not supported in this context
商汤自研机械臂,首款产品是AI下棋机器人:还请郭晶晶作代言
数字藏品,“赌”字当头
学习日记9
Makefile missing separator. Stop.怎么解决「建议收藏」
鸿蒙开发从hello world开始
Pod生命周期
【目标检测】小脚本:提取训练集图片与标签并更新索引
BEVDet4D: Exploit Temporal Cues in Multi-camera 3D Object Detection 论文笔记
ABAP 里文件操作涉及到中文字符集的问题和解决方案试读版
DNS欺骗-教程详解
bgp dual plane experiment routing strategy to control traffic