当前位置:网站首页>Promise learning (1) What is Promise?how to use?How to solve callback hell?
Promise learning (1) What is Promise?how to use?How to solve callback hell?
2022-08-01 10:33:00 【I'm sorry the user has become immortal】
目录
前言
Promise是什么
Promise概述
Promise 是异步编程的一种解决方案,它是ES6 Standardized a new technology.
- 从语法上讲,promise是一个对象、也是一个构造函数,从它可以获取异步操作的消息.
- 从本意上讲,it is also a promise,The promise will give you a result.
- 从功能上来说: promise 对象用来封装一个异步操作并可以获取其成功/ 失败的结果值.
Promise的状态
promise实例有三种状态:
- 异步操作未完成(
pending) - 异步操作成功(
resolved/fulfilled) - 异步操作失败(
rejected)
promise 的状态改变:
pending变为resolved/fulfilledpending变为rejected
状态只能改变一次,一旦改变,就不会再变,And there will be a result data,成功的结果数据一般称为 value, 失败的结果数据一般称为 reason
promise的基本流程

代码展示如下,我们只调取了成功的回调,The final result can be obtained as ‘okk’
const p = new Promise((resolve, reject) => {
// 异步语句 延时器
setTimeout(() => {
if ('异步操作成功') {
// 成功状态
resolve('okk');
} else {
// 失败状态
reject('err');
}
},1000);
});
// 调用 then 方法 指定回调
p.then(value => {
// 成功回调
console.log(value);
}, reason => {
// 失败回调
console.log(reason);
});
Let's talk about change here promise Status and the execution order of the specified callback function,Subsequent blogs will systematically update this part of the problem,这里我们只需要知道The data is only available when the state has changed,也就是说,当前状态由
pending变为resolved/fulfilled后,In order to get the successful callback data ‘okk’ .
为什么要用Promise
1. 指定回调函数的方式更加灵活
旧的: 必须在启动异步任务前指定
promise : 启动异步任务 => 返回promie对象 => 给promise对象绑定回调函数(甚至可以在异步任务结束后指定/多个)
2. 支持链式调用, 可以解决回调地狱问题
2.1 什么是回调地狱
回调地狱是指:多层嵌套函数,The return value of the function is the execution condition of the next function.
setTimeout(() => {
console.log('1');
setTimeout(() => {
console.log('2');
setTimeout(() => {
console.log('3');
}, 1000);
}, 2000);
}, 3000);

回调函数中嵌套回调函数的情况就叫做回调地狱,可以看到,There are three layers of delays nested above(Also a callback function),Finally output every one second‘1’,‘2’,‘3’
The disadvantage of callback hell is that it is not easy to read 不便于异常处理
2.2 原生PromiseChained solution
const test = n => {
return new Promise((resolve, reject) => {
// 异步任务
setTimeout(() => {
resolve(n);
}, 1000);
});
}
test(1).then(data => {
console.log(data);
return test(2);
}).then(data => {
console.log(data);
return test(3);
}).then(data => {
console.log(data);
}).catch(data => {
console.log(data);
});
2.3 Promise的async/await解决(终极方案)
const test1 = n => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(n)
}, 1000);
});
}
const test = async () => {
console.log(await test1(1));
console.log(await test1(2));
console.log(await test1(3));
}
test();
Promise A few common small cases
Promise 封装 fs 读取文件操作
/** * 封装一个函数 mineReadFile 读取文件内容 * 参数: path 文件路径 * 返回: promise 对象 */
let mineReadFile = (path) => {
return new Promise ((resolve, reject) => {
//读取文件
require('fs').readFile(path, (err, data) => {
// 判断
if (err) reject(err);
// 成功
resolve(data);
});
});
}
mineReadFile('./resource/content.txt').then(value => {
// 输出文件内容(成功)
console.log(value.toString());
}, reason => {
console.log(reason);
});
Promise 的 util.promisify 方法
The function can be turned directly into promise的封装方式,No more manual packaging
//引入 util 模块
const util = require('util');
//引入 fs 模块
const fs = require('fs');
//返回一个新的函数
let mineReadFile = util.promisify(fs.readFile);
mineReadFile('./resource/content.txt').then(value=>{
console.log(value.toString());
}, reason=> {
console.log(reason);
});
Promise 封装 Ajax 异步请求
/** * 封装一个函数 sendAJAX 发送 GET AJAX 请求 * 参数 URL * 返回结果 Promise 对象 */
const sendAJAX = (url) => {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.responseType = 'json';
xhr.open('GET', url);
xhr.send();
// 处理结果
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
// 判断成功
if(xhr.status >= 200 && xhr.status < 300) {
// A successful result is the response body
resolve(xhr.response);
} else {
reject(xhr.status);
}
}
}
});
}
sendAJAX('https://pagead2.googlesyndication.com/getconfig/sodar?sv=200&tid=gda&tv=r20220718&st=env').then(value => {
console.log(value);
}, reason => {
console.log(reason);
})
Some used in this articlePromise的API(如 then, catch等方法)见下一篇博客
Promise学习(二)An article takes you to a quick understandingPromise中的常用API
Authors: min
时间: 2022年7月24日
边栏推荐
- ModelArts-based object detection YOLOv3 practice [play with HUAWEI CLOUD]
- SAP ABAP OData 服务如何支持 $orderby (排序)操作试读版
- 浏览器快捷键大全
- Guangyu Mingdao was selected into the list of pilot demonstration projects for the development of digital economy industry in Chongqing in 2022
- Introduction and application of pointers
- .NET性能优化-使用SourceGenerator-Logger记录日志
- .NET深入解析LINQ框架(三:LINQ优雅的前奏)
- Android 安全与防护策略
- 50.【Application of dynamic two-dimensional array】
- PDMan-国产免费通用数据库建模工具(极简,漂亮)
猜你喜欢
随机推荐
PowerPC技术与市场杂谈
EasyRecovery热门免费数据检测修复软件
记一次 .NET 某智慧物流WCS系统CPU爆高分析
SQL Server database schema and objects related knowledge notes
Browser shortcut keys
分类预测 | MATLAB实现1-DCNN一维卷积神经网络分类预测
机器学习 | MATLAB实现支持向量机回归RegressionSVM参数设定
Yang Hui Triangle (C language implementation)
深度学习 | MATLAB实现一维卷积神经网络convolution1dLayer参数设定
AI篮球裁判火了,走步算得特别准,就问哈登慌不慌
【无标题】
Qt 支持HEIC/HEIF格式图片
回归预测 | MATLAB实现TPA-LSTM(时间注意力注意力机制长短期记忆神经网络)多输入单输出
retired paddling
Promise学习(一)Promise是什么?怎么用?回调地狱怎么解决?
关于#SQL#的问题,如何解决?
Mini Program Graduation Works WeChat Food Recipes Mini Program Graduation Design Finished Products (4) Opening Report
2022年7月31日--使用C#迈出第一步--使用C#中的数组和foreach语句来存储和循环访问数据序列
复现assert和eval成功连接或失败连接蚁剑的原因
notes....
![[Software Architecture Mode] The difference between MVVM mode and MVC mode](/img/37/8470ff9267752d4ca26a6b54ec0b50.png)







