当前位置:网站首页>Promise learning (4) The ultimate solution for asynchronous programming async + await: write asynchronous code in a synchronous way
Promise learning (4) The ultimate solution for asynchronous programming async + await: write asynchronous code in a synchronous way
2022-08-01 10:49:00 【I'm sorry the user has become immortal】
目录
前言
1. async 函数
ES2017 标准引入了 async
函数,使得异步操作变得更加方便. async
函数是使用 async
关键字声明的函数. async
函数是AsyncFunction构造函数的实例, 并且其中允许使用 await
关键字.async
和 await
Keywords allow us toWrite based on in a more concise wayPromise的异步行为,而无需刻意地链式调用promise.
async
是一个加在函数前的修饰符,被async
定义的函数会默认返回一个Promise对象resolve
的值.因此对async
函数可以直接then
,返回值就是then方法传入的函数.
- 函数的
返回值
为 promise 对象 - promise 对象的结果由
async
函数执行的返回值决定
async function main() {
//1. 如果返回值是一个非Promise类型的数据
// return 521; // 成功
//2. 如果返回的是一个Promise对象
// return new Promise((resolve, reject) => {
// // resolve('ok'); // 成功
// reject('err'); // 失败
// });
//3. 抛出异常
throw "失败了"; // 失败
};
let result = main();
console.log(result);
It can be seen that the result of execution is given by
async
The state of the function's return value is determined
2. await表达式
await
也是一个修饰符,只能放在async
定义的函数内.可以理解为等待
.await
后面可以跟任何的JS 表达式
.虽然说 await
可以等很多类型的东西,But it is primarily intended to be used等待 Promise 对象的状态被 resolved.如果await
的是 promiseThe object causes the asynchronous function to stop executing,并且等待 promise 的解决,如果等的是正常的表达式则立即执行
注意:
1.
await
可以理解为是async wait
的简写.await
必须出现在async
函数内部,不能单独使用.async
函数可以单独使用
2.await
主要是对Promise对象Successful result acquisition
3. 如果await
的 promise 失败了, 就会抛出异常, 需要通过try...catch
捕获处理
await
右侧的表达式一般为 promise 对象, 但也可以是其它的值- 如果表达式是 promise 对象,
await
返回的是 promise 成功的值 - 如果表达式是其它值, 直接将此值作为
await
的返回值
成功状态:
const main = async () => {
let p = new Promise((resolve, reject) => {
resolve('ok');
});
// 1. 右侧为promise的情况
let res1 = await p;
console.log(res1); // ok
//2. 右侧为其他类型的数据
let res2 = await 20;
console.log(res2); // 20
}
main();
失败状态(try...catch
捕获处理):
const main = async () => {
let p = new Promise((resolve, reject) => {
reject('err了');
});
// 如果promise是失败的状态
try {
let res3 = await p;
} catch(reason) {
console.log(reason);
}
}
main();
3. The ultimate solution to asynchronous programming async + await
先说一下Promiseunderstanding of the status of each task:
- Promise==>异步
- await==>异步转同步
- async==>同步转异步
Take an asynchronous example of callback hell:(回调地狱是指:多层嵌套函数,函数的返回值是下一个函数的执行条件.)
setTimeout(() => {
console.log('1');
setTimeout(() => {
console.log('2');
setTimeout(() => {
console.log('3');
}, 1000);
}, 2000);
}, 3000);
It will output sequentially every second
'1'
,'2'
,'3'
,回调地狱的The disadvantage is that it is not easy to read 不便于异常处理
解决方案:
- 原生Promise The way of chaining calls is in the front Promise学习(一)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();
这样做的
好处
是:结构清晰
,便于阅读
,方便异常处理
(如果抛出了异常,可以用try...catch
处理异常),这里为了方便理解,Use the success status directly.
4. async 和 await 结合实践1:读取文件信息
小案例1:读取 1.html 2.html 3.html 三个文件内容,有两种方法,一是回调函数
形式实现,二是 async
+ await
实现.
1. 回调函数形式:
// 引入fs模块
const fs = require('fs');
//回调函数的方式
fs.readFile('./resource/1.html', (err, data1) => {
if (err) throw error;
fs.readFile('./resource/2.html', (err, data2) => {
if (err) throw error;
fs.readFile('./resource/3.html', (err, data3) => {
if (err) throw error;
console.log(data1 + data2 + data3);
});
});
});
Open integrated terminal input node .\The current filename to run
,That is, the contents of three files can be read.
2.
async
+await
实现:
// 引入fs模块
const fs = require('fs');
//引入 util 模块
// util.promisify methods can directly turn functions into promise的封装方式,不用再去手动封装
const util = require('util');
const mineReadFile = util.promisify(fs.readFile);
//async 与 await 实现
const main = async () => {
try{
//读取第一个文件的内容
let data1 = await mineReadFile('./resource/1xxx.html'); // 错误文件
let data2 = await mineReadFile('./resource/2.html');
let data3 = await mineReadFile('./resource/3.html');
console.log(data1 + data2 + data3);
}catch(e){
console.log(e); // error will prompt
console.log(e.code); // an attribute in the error
}
}
main();
If the filenames are correct, you will get the same result as the callback function implementation,When we enter the wrong filename,最后可以得到
try...catch
Information about the error that was handled
5. async 和 await 结合实践2:结合Ajax获取接口信息
小案例2:结合Ajax获取接口信息, async
+ await
实现.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<button id="btn">点击获取段子</button>
<script> const sendAJAX = url => {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest(); xhr.responseType = 'json'; xhr.open("GET", url); xhr.send(); //处理结果 xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
//判断成功 if(xhr.status >= 200 && xhr.status < 300){
//成功的结果 resolve(xhr.response); }else{
reject(xhr.status); } } } }) } $("#btn").click(async () => {
// Get interface text information let datas = await sendAJAX('https://pagead2.googlesyndication.com/getconfig/sodar?sv=200&tid=gda&tv=r20220718&st=env'); console.log(datas); }); </script>
</body>
</html>
Pay attention to the cross-domain problem of the interface
这里提一下
跨域问题
,Because you will not write your own interface,Many interfaces found on the Internet have cross-domain problems,So we need to see clearly when choosing an interface网络
中有无CORS错误
的字眼,Cross-domain interfaces cannot successfully return data.
至此,PromiseThe study chapter is temporarily over,If there are more supplements, we will continue to update,Please continue to support if you find it helpful!
Authors: min
时间: 2022年7月27日
边栏推荐
- 昇思大模型体验平台初体验——以小模型LeNet为例
- 解决vscode输入! 无法快捷生成骨架(新版vscode快速生成骨架的三种方法)
- Dapr 与 NestJs ,实战编写一个 Pub & Sub 装饰器
- Browser shortcut keys
- 2022年中盘点 | 产品打底,科技背书,广汽集团阔步向前
- Py之yellowbrick:yellowbrick的简介、安装、使用方法之详细攻略
- Kaitian aPaaS mobile phone number empty number detection [Kaitian aPaaS battle]
- CTFshow,命令执行:web37
- 如何从完美的智能合约中窃取 1 亿美元
- 退役划水
猜你喜欢
.NET性能优化-使用SourceGenerator-Logger记录日志
Android 安全与防护策略
一文说明白ECDSA spec256k1 spec256r1 EdDSA ed25519千丝万缕的关系
解决vscode输入! 无法快捷生成骨架(新版vscode快速生成骨架的三种方法)
gc的意义和触发条件
PowerPC技术与市场杂谈
石头科技打造硬核品牌力 持续出海拓展全球市场
图解MySQL内连接、外连接、左连接、右连接、全连接......太多了
Promise to learn several key questions (3) the Promise - state change, execution sequence and mechanism, multitasking series, abnormal penetration, interrupt the chain of Promise
MacOS下postgresql(pgsql)数据库密码为什么不需要填写或可以乱填写
随机推荐
周鸿祎称微软抄袭 360 安全模式后发文否认;英特尔CEO基辛格回应市值被AMD超越:股价下跌是咎由自取|极客头条
【cartographer ros】10: Delay and error analysis
InputStream转成String
shell--面试题
Taobao commodity details and details on taobao, senior upgrade version of the API
NIO‘s Sword(思维,取模,推公式)
Custom Types - Enums, Unions
Guangyu Mingdao was selected into the list of pilot demonstration projects for the development of digital economy industry in Chongqing in 2022
Glassmorphism design style
URL.createObjectURL、URL.revokeObjectURL、Uint8Array、Blob使用详解
冰冰学习笔记:gcc、gdb等工具的使用
力扣解法汇总1374-生成每种字符都是奇数个的字符串
Basic configuration commands of cisco switches (what is the save command of Huawei switches)
【无标题】
从零开始Blazor Server(4)--登录系统
How to find out hidden computer software (how to clean up the computer software hidden)
在线GC日志分析工具——GCeasy
深度学习 | MATLAB实现一维卷积神经网络convolution1dLayer参数设定
PDMan-domestic free general database modeling tool (minimalist, beautiful)
STM32 Personal Notes - Embedded C Language Optimization