当前位置:网站首页>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日
边栏推荐
- 阿里腾讯面试一二
- Promise to learn several key questions (3) the Promise - state change, execution sequence and mechanism, multitasking series, abnormal penetration, interrupt the chain of Promise
- 怎么找出电脑隐藏的软件(如何清理电脑隐藏软件)
- C#/VB.NET 将PPT或PPTX转换为图像
- retired paddling
- ClickHouse入门介绍与其特性
- 【cartographer ros】十: 延时和误差分析
- Endorsed in 2022 years inventory | product base, science and technology, guangzhou automobile group striding forward
- CTO strongly banning the use of the Calendar, that in what?
- WPF 截图控件之绘制箭头(五)「仿微信」
猜你喜欢
How to Steal $100 Million from the Perfect Smart Contract
Promise学习(三)Promise的几个关键性问题 -- 状态改变、执行顺序与机制、多任务串联、异常穿透、中断promise链
退役划水
各位大拿,安装Solaris 11.4操作系统,在安装数据库依赖包的时候包这个错,目前无原厂支持,也无安装盘,联网下载后报这个错,请教怎么解决?
【钛晨报】国家统计局:7月制造业PMI为49%;玖富旗下理财产品涉嫌欺诈,涉及390亿元;国内航线机票燃油附加费8月5日0时起下调
The meaning and trigger conditions of gc
CTFshow,命令执行:web32
Qt supports HEIC/HEIF format images
Py之yellowbrick:yellowbrick的简介、安装、使用方法之详细攻略
回归预测 | MATLAB实现TPA-LSTM(时间注意力注意力机制长短期记忆神经网络)多输入单输出
随机推荐
C语言程序设计50例(三)(经典收藏)
Promise learning (2) An article takes you to quickly understand the common APIs in Promise
Mini Program Graduation Works WeChat Food Recipes Mini Program Graduation Design Finished Products (4) Opening Report
2022年7月31日--使用C#迈出第一步--使用 C# 创建具有约定、空格和注释的易读代码
How I secured 70,000 ETH and won a 6 million bug bounty
4种常见的鉴权方式及说明
retired paddling
Generate certificates using KeyStore
CTFshow,命令执行:web34、35、36
回归预测 | MATLAB实现RNN循环神经网络多输入单输出数据预测
使用KeyStore生成证书
小程序毕设作品之微信美食菜谱小程序毕业设计成品(2)小程序功能
Mini Program Graduation Works WeChat Food Recipes Mini Program Graduation Design Finished Products (2) Mini Program Functions
xss漏洞学习
广域铭岛入选2022年重庆市数字经济产业发展试点示范项目名单
ModelArts-based object detection YOLOv3 practice [play with HUAWEI CLOUD]
PowerPC技术与市场杂谈
MySQL 必现之死锁
C#/VB.NET 将PPT或PPTX转换为图像
The meaning and trigger conditions of gc