手写promis(2)-- 链式编程篇

目录

链式编程 处理异常 和普通内容

链式编程---处理返回promise

链式编程---处理重复引用

链式编程--rejected 

链式编程--处理padding状态


链式编程 处理异常 和普通内容

  • 1.返回promise实例:在原本then方法里边创建新promise
  • 2.获取返回值:把原本的then的逻辑迁移到新promise中 是同步执行的不受影响(方便传递给新创建的promise)
  • 3.处理返回值 调用新promise的 resolve 
  • 4.处理异常 try catch 捕获异常 调用新promise的 reject

function runAsyncTask(callback) {if (typeof queueMicrotask === "function") {queueMicrotask(callback);} else if (typeof MutationObserver == "function") {const obs = new MutationObserver(callback);const divNode = document.createElement("div");obs.observe(divNode, { childList: true });divNode.innerHTML = "贾公子";} else {setTimeout(callback, 0);}
}/**链式编程 处理异常 和普通内容*   1.返回promise实例*   2.获取返回值*    2.1处理返回值*    2.2处理异常***/
const PENDING = "pending";
const FULFILLED = "fulfilled";
const REJECTED = "rejected";class MyPromise {state = PENDING;result = undefined;#handlers = [];constructor(func) {const resolve = (result) => {if (this.state == PENDING) {this.state = FULFILLED;this.result = result;this.#handlers.forEach(({ onFulfilled }) => {onFulfilled(this.result);});}};const reject = (result) => {if (this.state == PENDING) {this.state = REJECTED;this.result = result;this.#handlers.forEach(({ onRejected }) => {onRejected(this.result);});}};func(resolve, reject);}then(onFulfilled, onRejected) {onFulfilled = typeof onFulfilled === "function" ? onFulfilled : (x) => x;onRejected =typeof onRejected === "function"? onRejected: (x) => {throw x;};//  1.返回promise实例const p2 = new MyPromise((resolve, reject) => {if (this.state === FULFILLED) {runAsyncTask(() => {try {// 2.获取返回值const x = onFulfilled(this.result);// 2.1处理返回值resolve(x);// 2.2处理异常} catch (error) {reject(error);}});} else if (this.state === REJECTED) {runAsyncTask(() => {onRejected(this.result);});} else if (this.state === PENDING) {this.#handlers.push({onFulfilled: () => {runAsyncTask(() => {onFulfilled(this.result);});},onRejected: () => {runAsyncTask(() => {onRejected(this.result);});},});}});return p2;}
}// 测试代码const p = new MyPromise((resolve, reject) => {resolve("1");// reject("error");
});
p.then((result) => {console.log("p1", result);throw new Error("异常");// return 2;
}).then((result) => {console.log("p2", result);},(err) => {console.log("p2", err);}
);

链式编程---处理返回promise

1.使用 instanceof判断返回值是否为 MyPromise实例

2.如果是代表传递的返回值是promise 调用传递的promise的then方法

3.在成功回调中调用resolve,失败回调中传递reject,把结果传递

function runAsyncTask(callback) {if (typeof queueMicrotask === "function") {queueMicrotask(callback);} else if (typeof MutationObserver == "function") {const obs = new MutationObserver(callback);const divNode = document.createElement("div");obs.observe(divNode, { childList: true });divNode.innerHTML = "贾公子";} else {setTimeout(callback, 0);}
}/****/
const PENDING = "pending";
const FULFILLED = "fulfilled";
const REJECTED = "rejected";class MyPromise {state = PENDING;result = undefined;#handlers = [];constructor(func) {const resolve = (result) => {if (this.state == PENDING) {this.state = FULFILLED;this.result = result;this.#handlers.forEach(({ onFulfilled }) => {onFulfilled(this.result);});}};const reject = (result) => {if (this.state == PENDING) {this.state = REJECTED;this.result = result;this.#handlers.forEach(({ onRejected }) => {onRejected(this.result);});}};func(resolve, reject);}then(onFulfilled, onRejected) {onFulfilled = typeof onFulfilled === "function" ? onFulfilled : (x) => x;onRejected =typeof onRejected === "function"? onRejected: (x) => {throw x;};const p2 = new MyPromise((resolve, reject) => {if (this.state === FULFILLED) {runAsyncTask(() => {try {const x = onFulfilled(this.result);// 1.处理返回promiseif (x instanceof MyPromise) {// 2.调用then方法x.then((res) => {resolve(res);},(err) => {reject(err);});} else {resolve(x);}} catch (error) {reject(error);}});} else if (this.state === REJECTED) {runAsyncTask(() => {onRejected(this.result);});} else if (this.state === PENDING) {this.#handlers.push({onFulfilled: () => {runAsyncTask(() => {onFulfilled(this.result);});},onRejected: () => {runAsyncTask(() => {onRejected(this.result);});},});}});return p2;}
}// 测试代码const p = new MyPromise((resolve, reject) => {resolve("1");
});
p.then((result) => {return new MyPromise((resolve, reject) => {resolve(2);// reject("err");});
}).then((result) => {console.log("p2", result);},(err) => {console.log("p2", err);}
);

链式编程---处理重复引用

在then的回调函数中直接把then的结果返回了会抛出重复引用的问题

1.x就是then回调函数的返回值,then方法返回的promise就是p2

2.比较x跟p2是否全等 是就抛出异常 

function runAsyncTask(callback) {if (typeof queueMicrotask === "function") {queueMicrotask(callback);} else if (typeof MutationObserver == "function") {const obs = new MutationObserver(callback);const divNode = document.createElement("div");obs.observe(divNode, { childList: true });divNode.innerHTML = "贾公子";} else {setTimeout(callback, 0);}
}const PENDING = "pending";
const FULFILLED = "fulfilled";
const REJECTED = "rejected";class MyPromise {state = PENDING;result = undefined;#handlers = [];constructor(func) {const resolve = (result) => {if (this.state == PENDING) {this.state = FULFILLED;this.result = result;this.#handlers.forEach(({ onFulfilled }) => {onFulfilled(this.result);});}};const reject = (result) => {if (this.state == PENDING) {this.state = REJECTED;this.result = result;this.#handlers.forEach(({ onRejected }) => {onRejected(this.result);});}};func(resolve, reject);}then(onFulfilled, onRejected) {onFulfilled = typeof onFulfilled === "function" ? onFulfilled : (x) => x;onRejected =typeof onRejected === "function"? onRejected: (x) => {throw x;};const p2 = new MyPromise((resolve, reject) => {if (this.state === FULFILLED) {runAsyncTask(() => {try {const x = onFulfilled(this.result);// 1.处理重复的引用if (x === p2) {console.log("----");throw new TypeError("Chaining cycle detected for promise #<Promise>");}if (x instanceof MyPromise) {x.then((res) => {resolve(res);},(err) => {reject(err);});} else {resolve(x);}} catch (error) {reject(error);}});} else if (this.state === REJECTED) {runAsyncTask(() => {onRejected(this.result);});} else if (this.state === PENDING) {this.#handlers.push({onFulfilled: () => {runAsyncTask(() => {onFulfilled(this.result);});},onRejected: () => {runAsyncTask(() => {onRejected(this.result);});},});}});return p2;}
}// 测试代码const p = new MyPromise((resolve, reject) => {resolve("1");
});
const p2 = p.then((res) => {return p2;
});
p2.then((res) => {},(err) => {console.log(err);}
);

链式编程--rejected 

完成链式第一步要返回promise 处理Fulfilled时候已完成

通过trycatch 处理异常

抽离函数 resolvePromise 处理 重复引用 以及返回promise的情况

调用函数测试状态

function runAsyncTask(callback) {if (typeof queueMicrotask === "function") {queueMicrotask(callback);} else if (typeof MutationObserver == "function") {const obs = new MutationObserver(callback);const divNode = document.createElement("div");obs.observe(divNode, { childList: true });divNode.innerHTML = "贾公子";} else {setTimeout(callback, 0);}
}const PENDING = "pending";
const FULFILLED = "fulfilled";
const REJECTED = "rejected";class MyPromise {state = PENDING;result = undefined;#handlers = [];constructor(func) {const resolve = (result) => {if (this.state == PENDING) {this.state = FULFILLED;this.result = result;this.#handlers.forEach(({ onFulfilled }) => {onFulfilled(this.result);});}};const reject = (result) => {if (this.state == PENDING) {this.state = REJECTED;this.result = result;this.#handlers.forEach(({ onRejected }) => {onRejected(this.result);});}};func(resolve, reject);}/***处理异常*/then(onFulfilled, onRejected) {onFulfilled = typeof onFulfilled === "function" ? onFulfilled : (x) => x;onRejected =typeof onRejected === "function"? onRejected: (x) => {throw x;};const p2 = new MyPromise((resolve, reject) => {if (this.state === FULFILLED) {runAsyncTask(() => {try {const x = onFulfilled(this.result);resolvePromise(p2, x, resolve, reject);} catch (error) {reject(error);}});} else if (this.state === REJECTED) {// 1.处理异常runAsyncTask(() => {try {// 2.获取返回值const x = onRejected(this.result);// 4.调用函数resolvePromise(p2, x, resolve, reject);} catch (error) {reject(error);}});} else if (this.state === PENDING) {this.#handlers.push({onFulfilled: () => {runAsyncTask(() => {onFulfilled(this.result);});},onRejected: () => {runAsyncTask(() => {onRejected(this.result);});},});}});return p2;}
}
// 3.抽取函数
function resolvePromise(p2, x, resolve, reject) {if (x === p2) {throw new TypeError("Chaining cycle detected for promise #<Promise>");}if (x instanceof MyPromise) {x.then((res) => {resolve(res);},(err) => {reject(err);});} else {resolve(x);}
}// 测试代码const p = new MyPromise((resolve, reject) => {reject("1");
});
const p2 = p.then(undefined, (err) => {// throw "error";// return p2;// return 2;return new MyPromise((resolve, reject) => {resolve("OK");reject("ERROR");});
});
p2.then((res) => {console.log("p2--res", res);},(err) => {console.log("p2--err", err);}
);

链式编程--处理padding状态

PENDING状态要根据异步执行的结果存储到handlers数组中不同的函数(onFulfilled || onRejected)两个处理链式编程的逻辑完全一样

   * 处理异常 trycatch捕获异常

   * 获取返回值 获取第一个promise的返回值

   * 调用函数 处理 重复引用以及 返回promise的情况

function runAsyncTask(callback) {if (typeof queueMicrotask === "function") {queueMicrotask(callback);} else if (typeof MutationObserver == "function") {const obs = new MutationObserver(callback);const divNode = document.createElement("div");obs.observe(divNode, { childList: true });divNode.innerHTML = "贾公子";} else {setTimeout(callback, 0);}
}function resolvePromise(p2, x, resolve, reject) {if (x === p2) {throw new TypeError("Chaining cycle detected for promise #<Promise>");}if (x instanceof MyPromise) {x.then((res) => {resolve(res);},(err) => {reject(err);});} else {resolve(x);}
}
const PENDING = "pending";
const FULFILLED = "fulfilled";
const REJECTED = "rejected";class MyPromise {state = PENDING;result = undefined;#handlers = [];constructor(func) {const resolve = (result) => {if (this.state == PENDING) {this.state = FULFILLED;this.result = result;this.#handlers.forEach(({ onFulfilled }) => {onFulfilled(this.result);});}};const reject = (result) => {if (this.state == PENDING) {this.state = REJECTED;this.result = result;this.#handlers.forEach(({ onRejected }) => {onRejected(this.result);});}};func(resolve, reject);}/*** 处理异常* 获取返回值* 调用函数*/then(onFulfilled, onRejected) {onFulfilled = typeof onFulfilled === "function" ? onFulfilled : (x) => x;onRejected =typeof onRejected === "function"? onRejected: (x) => {throw x;};const p2 = new MyPromise((resolve, reject) => {if (this.state === FULFILLED) {runAsyncTask(() => {try {const x = onFulfilled(this.result);resolvePromise(p2, x, resolve, reject);} catch (error) {reject(error);}});} else if (this.state === REJECTED) {runAsyncTask(() => {try {const x = onRejected(this.result);resolvePromise(p2, x, resolve, reject);} catch (error) {reject(error);}});} else if (this.state === PENDING) {this.#handlers.push({onFulfilled: () => {runAsyncTask(() => {// 处理异常try {// 获取返回值const x = onFulfilled(this.result);//  调用函数resolvePromise(p2, x, resolve, reject);} catch (error) {reject(error);}});},onRejected: () => {runAsyncTask(() => {// 处理异常try {// 获取返回值const x = onRejected(this.result);//  调用函数resolvePromise(p2, x, resolve, reject);} catch (error) {reject(error);}});},});}});return p2;}
}// 测试代码const p = new MyPromise((resolve, reject) => {setTimeout(() => {resolve("1");}, 2000);
});
const p2 = p.then((res) => {// throw "error";// return p2;// return 2;return new MyPromise((resolve, reject) => {setTimeout(() => {resolve("OK");}, 2000);// reject("ERROR");});
});
p2.then((res) => {console.log("p2--res", res);},(err) => {console.log("p2--err", err);}
);

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/158138.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

基于安卓android微信小程序的小型企业人力资源管理系统-人事考勤app

运行环境 开发语言&#xff1a;Java 框架&#xff1a;ssm JDK版本&#xff1a;JDK1.8 服务器&#xff1a;tomcat7 小程序框架&#xff1a;uniapp 小程序开发软件&#xff1a;HBuilder X 小程序运行软件&#xff1a;微信开发者 项目介绍 基于微信小程序的小型企业人力资源管…

C语言基本算法之选择排序

目录 概要&#xff1a; 代码如下 运行结果如下 概要&#xff1a; 它和冒泡排序一样&#xff0c;都是把数组元素按顺序排列&#xff0c;但是方法不同&#xff0c;冒泡排序是把较小值一个一个往后面移&#xff0c;选择排序则是直接找出最小值&#xff0c;可以这个说&#xff…

Python+OpenCV裂缝面积识别系统(部署教程&源码)

1.研究背景与意义 随着科技的不断发展&#xff0c;计算机视觉技术在各个领域中得到了广泛的应用。其中&#xff0c;图像处理是计算机视觉中的一个重要分支&#xff0c;它通过对图像进行数字化处理&#xff0c;提取出其中的有用信息&#xff0c;为后续的分析和应用提供支持。而…

2023.11.22 -数据仓库

目录 https://blog.csdn.net/m0_49956154/article/details/134320307?spm1001.2014.3001.5501 1经典传统数仓架构 2离线大数据数仓架构 3数据仓库三层 数据运营层,源数据层&#xff08;ODS&#xff09;&#xff08;Operational Data Store&#xff09; 数据仓库层&#…

新生儿近视:原因、科普和注意事项

引言&#xff1a; 近年来&#xff0c;新生儿近视的发病率逐渐上升&#xff0c;引起了广泛关注。新生儿近视的原因复杂&#xff0c;可能受到遗传、环境和行为等多方面因素的影响。本文将深入解析新生儿近视的原因&#xff0c;提供相关科普知识&#xff0c;并为父母和监护人提供…

线性代数 - 几何原理

目录 序言向量的定义线性组合、张成空间与向量基线性变换和矩阵线性复合变换与矩阵乘法三维空间的线性变换行列式矩阵的秩和逆矩阵维度变换点乘叉乘基变换特征值和特征向量抽象向量空间 序言 欢迎阅读这篇关于线性代数的文章。在这里&#xff0c;我们将从一个全新的角度去探索线…

酒店预订订房小程序源码系统+多酒店入驻 功能齐全 附带完整的搭建教程

随着互联网的快速发展&#xff0c;越来越多的人选择通过在线预订平台预订酒店。为了满足这一需求&#xff0c;我们开发了这个酒店预订订房小程序源码系统。该系统基于先进的云计算技术和大数据分析&#xff0c;旨在为用户提供更加便捷、智能的酒店预订服务。 以下是部分代码示…

排序算法--选择排序

实现逻辑 ① 第一轮从下标为 1 到下标为 n-1 的元素中选取最小值&#xff0c;若小于第一个数&#xff0c;则交换 ② 第二轮从下标为 2 到下标为 n-1 的元素中选取最小值&#xff0c;若小于第二个数&#xff0c;则交换 ③ 依次类推下去…… void print_array(int a[], int n){f…

MySQL 数据库下载

1 最新版 MySQL :: Download MySQL Community Server 2 存档版本(Archived Versions)-历史版本 MySQL :: Download MySQL Community Server (Archived Versions) 3 下载(样例: zip 方式) tip1&#xff1a; 可以下载安装文件的方式&#xff0c;也可以使用压缩包方式&#xff…

健康饮酒进家庭,国台酒业与碧桂园服务集团达成战略合作

11月19日&#xff0c;碧桂园服务集团与国台酒业集团战略合作发布会暨“健康饮酒进家庭”项目启动仪式在广州举行。 广东省酒类行业协会创会会长朱思旭&#xff0c;广东省酒类行业协会会长彭洪&#xff0c;碧桂园服务集团总裁徐彬淮&#xff0c;碧桂园服务集团酒类业务总经理、广…

便携式自动气象站让你随时随地掌握天气变化

WX-BXQX12 随着科技的发展&#xff0c;人们对气象信息的掌握越来越重要。无论是在日常生活中&#xff0c;还是在农业生产、旅游出行等领域&#xff0c;了解天气变化都显得至关重要。为了满足人们对气象信息的需求&#xff0c;一款名为“便携式自动气象站”的创新产品应运而生。…

Java 下载地址

1 地址&#xff1a; Java Downloads | Oracle 2 往下翻(Java 8 和 Java 11) 3 往下翻 (JRE 下载)(JRE 8 为例) 4 跳转到登录(登录账号才可以下载)

suricata识别菜刀流量

一、捕获菜刀流量 payload特征&#xff1a; PHP: <?php eval($_POST[caidao]);?> ​ ASP: <%eval request(“caidao”)%> ​ ASP.NET: <% Page Language“Jscript”%><%eval(Request.Item[“caidao”],“unsafe”);%>数据包流量特征&#xff1a; …

解密高性能查询!小米亲授:如何轻松查出1000条数据的后十条前7条?

大家好&#xff0c;我是小米&#xff01;今天要跟大家分享一道火辣辣的面试题&#xff1a;在一张表中&#xff0c;如何高性能地查出1000条数据的后十条的前7条&#xff1f;这可是一个考察你数据库查询优化能力的好题目哦&#xff01;废话不多说&#xff0c;让我们直奔主题&…

扩散模型实战(十一):剖析Stable Diffusion Pipeline各个组件

推荐阅读列表&#xff1a; 扩散模型实战&#xff08;一&#xff09;&#xff1a;基本原理介绍 扩散模型实战&#xff08;二&#xff09;&#xff1a;扩散模型的发展 扩散模型实战&#xff08;三&#xff09;&#xff1a;扩散模型的应用 扩散模型实战&#xff08;四&#xff…

深圳锐科达SV-X7 sip话机与海康威视摄像头联动设置方法

深圳锐科达SV-X7 sip话机与海康威视摄像头联动设置方法 SIP对讲终端获取设备IP地址方式 通过长按速拨键3秒&#xff08;上电30秒后&#xff0c;即听到提示音后&#xff09;&#xff0c;待喇叭发出急促嘟嘟声&#xff0c;再快速按一下速拨键&#xff0c;设备自动语音播报本机的…

Transformer——encoder

本文参考了b站的Eve的科学频道中的深入浅出解释Transformer原理和DASOU讲AI中的Transformer从零详解。 入浅出解释Transformer原理 Transformer从零详解 前言&#xff1a; 在自然语言识别中&#xff0c;之前讲过lstm&#xff0c;但是lstm有明显的缺陷&#xff0c;就是当文本过…

从传统到智能 | 拓世法宝AI智能直播一体机为商家注入活力

2023年即将结束&#xff0c;直播仍然是商业舞台上的主旋律&#xff0c;本地生活也不例外。据数据显示&#xff0c;到2022年&#xff0c;中国本地生活服务市场规模已经达到29.8万亿元&#xff0c;而预计到2025年&#xff0c;这一数字将继续攀升至35.3万亿元。伴随着当地生活直播…

Arguments对象

Arguments 对象 arguments 基本定义 首先arguments是以内置对象出现的。换句话说&#xff1a;你不能够直接的去访问arguments对象&#xff0c;所以你会返现在浏览器中直接访问arguments对象是不存在的。 特别重要&#xff1a; 那么arguments对象本质上是什么东西呢&#xff…

Java零基础——Spring篇

1.Spring框架的介绍 1.1 传统的项目的架构 在传统的项目中&#xff0c;一般遵循MVC开发模型。 (1) view层与用户进行交互&#xff0c;显示数据或者将数据传输给view层。 (2) 在controller层创建service层对象&#xff0c;调用service层中业务方法。 (3) 在service层创建dao…