当前位置:网站首页>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日
边栏推荐
- Introduction to data warehouse layering (real-time data warehouse architecture)
- 编码解码(btoa、encodeURIComponent、encodeURI、escape)
- C语言程序设计50例(三)(经典收藏)
- 报告:想学AI的学生数量已涨200%,老师都不够用了
- 2022年7月31日--使用C#迈出第一步--使用 C# 创建具有约定、空格和注释的易读代码
- ModelArts-based object detection YOLOv3 practice [play with HUAWEI CLOUD]
- experiment....
- 基于ModelArts的物体检测YOLOv3实践【玩转华为云】
- 世界第4疯狂的科学家,在103岁生日那天去世了
- SQL Server database schema and objects related knowledge notes
猜你喜欢

Endorsed in 2022 years inventory | product base, science and technology, guangzhou automobile group striding forward

redis

【钛晨报】国家统计局:7月制造业PMI为49%;玖富旗下理财产品涉嫌欺诈,涉及390亿元;国内航线机票燃油附加费8月5日0时起下调

50.【Application of dynamic two-dimensional array】

进制与转换、关键字

Message queue interview latest finishing (2022)

Android 安全与防护策略

基于CAP组件实现补偿事务与消息幂等性

jmeter

微信公众号授权登录后报redirect_uri参数错误的问题
随机推荐
Batch大小不一定是2的n次幂!ML资深学者最新结论
Three chess (C language implementation)
Android 安全与防护策略
Dataset之mpg:mpg数据集的简介、下载、使用方法之详细攻略
Android Security and Protection Policy
C语言程序设计50例(三)(经典收藏)
一文说明白ECDSA spec256k1 spec256r1 EdDSA ed25519千丝万缕的关系
July 31, 2022 -- Take your first steps with C# -- Use arrays and foreach statements in C# to store and iterate through sequences of data
CTFshow,命令执行:web33
notes....
MacOS下postgresql(pgsql)数据库密码为什么不需要填写或可以乱填写
JWT
深度学习 | MATLAB实现一维卷积神经网络convolution1dLayer参数设定
C language game - minesweeper
基于CAP组件实现补偿事务与消息幂等性
4种常见的鉴权方式及说明
【云驻共创】分布式技术之华为云全域调度技术与实践
The first experience of Shengsi large model experience platform——Take the small model LeNet as an example
Custom Types - Enums, Unions
回归预测 | MATLAB实现TPA-LSTM(时间注意力注意力机制长短期记忆神经网络)多输入单输出