网站首页 > 博客文章 正文
异步编程的形式
+ 回调函数
+ 发布订阅模式
let dep = {
list: [],
on: function(fn) {
this.list.push(fn);
},
emit: function() {
this.list.forEach(f => typeof f === 'function' ? f() : null)
}
}
+ promise
+ async和await
介绍下Promise,内部实现
Promise 也还是使用回调函数,只不过是把回调封装在了内部,使用上一直通过 then 方法的链式调用,使得多层的回调嵌套看起来变成了同一层的,书写上以及理解上会更直观和简洁一些。
> 状态: pending、fulfilled、rejected。
class Promise {
callbacks = [];
errorCbs = [];
state = 'pending';
value = null;
constructor(fn) {
fn(this.resolve.bind(this), this.reject.bind(this))
}
resolve(value) {
this.state = 'fulfilled';
this.value = value;
this.callbacks.forEach((f) => f(value))
}
reject(value) {
this.state = 'rejeted';
this.value = value;
this.callbacks.forEach((f) => f(value))
}
then(onFulfilled, onRejected) {
if (this.state === 'pending') { //在resolve之前,跟之前逻辑一样,添加到callbacks中
this.callbacks.push(onFulfilled);
this.errorCbs.push(onRejected);
} else if (this.state === 'fulfilled') { //在resolve之后,直接执行回调,返回结果了
onFulfilled(this.value);
} else {
onRejected(this.value);
}
return this;
}
}
promise、async有什么区别
如何设计Promise.all()
介绍Promise,异常捕获,Promise和Async处理失败的时候有什么区别
若是在promise的.then中出现错误的话,外层的trycatch代码块是捕获不到错误的,所以就需要再加一层.catch,才能捕获到.then里面的报错,但是这样会显得代码有点冗余。而假如写成注释的async/await的格式,一个try/catch可以同时对同步以及异步进行错误处理,代码更加简洁。
介绍下Promise的用途和性质Promise和Callback有什么区别
Async/Await怎么实现
Promise和setTimeout执行先后的区别(Event Loop)
JS为什么要区分微任务和宏任务
Promise构造函数是同步还是异步执行,then呢
a,b两个按钮,点击aba,返回顺序可能是baa,如何保证是aba(Promise.then)
Async里面有多个await请求,可以怎么优化(请求是否有依赖)
猜你喜欢
- 2024-09-27 搞懂ES6语法之promise-那些常用姿势
- 2024-09-27 抢先熟悉ES2021新特性(es2021 新特性)
- 2024-09-27 JavaScript: Promises 介绍及为何 Async/Await 最终取得胜利
- 2024-09-27 种草 ES2020 八大新功能(es2020特性)
- 2024-09-27 碎片时间学编程「21]:异步 JavaScript 备忘总结
- 2024-09-27 async异步操作函数(async await异步请求)
- 2024-09-27 nodejs入门教程之Promise(十)(nodejs.)
- 2024-09-27 【JavaScript】ES6之Promise用法详解及其应用
- 2024-09-27 JavaScript,ES11,Promise.allSettled,返回一个Promise对象
- 2024-09-27 JavaScript中的Promise:异步编程的利器
你 发表评论:
欢迎- 最近发表
-
- 给3D Slicer添加Python第三方插件库
- Python自动化——pytest常用插件详解
- Pycharm下安装MicroPython Tools插件(ESP32开发板)
- IntelliJ IDEA 2025.1.3 发布(idea 2020)
- IDEA+Continue插件+DeepSeek:开发者效率飙升的「三体组合」!
- Cursor:提升Python开发效率的必备IDE及插件安装指南
- 日本旅行时想借厕所、买香烟怎么办?便利商店里能解决大问题!
- 11天!日本史上最长黄金周来了!旅游万金句总结!
- 北川景子&DAIGO缘定1.11 召开记者会宣布结婚
- PIKO‘PPAP’ 洗脑歌登上美国告示牌
- 标签列表
-
- ifneq (61)
- messagesource (56)
- aspose.pdf破解版 (56)
- promise.race (63)
- 2019cad序列号和密钥激活码 (62)
- window.performance (66)
- qt删除文件夹 (72)
- mysqlcaching_sha2_password (64)
- ubuntu升级gcc (58)
- nacos启动失败 (64)
- ssh-add (70)
- jwt漏洞 (58)
- macos14下载 (58)
- yarnnode (62)
- abstractqueuedsynchronizer (64)
- source~/.bashrc没有那个文件或目录 (65)
- springboot整合activiti工作流 (70)
- jmeter插件下载 (61)
- 抓包分析 (60)
- idea创建mavenweb项目 (65)
- vue回到顶部 (57)
- qcombobox样式表 (68)
- vue数组concat (56)
- tomcatundertow (58)
- pastemac (61)
本文暂时没有评论,来添加一个吧(●'◡'●)