当前位置:网站首页>Promise从入门到精通(第4章 async 和 await)
Promise从入门到精通(第4章 async 和 await)
2022-07-28 00:41:00 【若水cjj】
Promise从入门到精通(第4章 async 和 await)
第4章 async 和 await
4.1. mdn文档
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/async_function
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/await
4.2. async函数
函数的返回值为 promise 对象
promise 对象的结果由 async 函数执行的返回值决定(和then的特性相同)
<!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>
</head>
<body>
<script> // async函数返回结果是一个Promise async function main(){
// 1.如果返回值是一个非Promise,那么返回的Promise状态为fulfilled,结果值为返回的结果 // return "123"; // 2.如果返回值是一个Promise,那么返回的Promise状态为Promise的状态,结果值为Promise返回的结果 // return new Promise((resolve,reject)=>{
// reject("123"); // }); // 3.如果返回值是抛出的异常,那么返回的Promise状态为reject,结果值为抛出的异常 throw "error"; } let result = main() console.log(result); </script>
</body>
</html>
4.3 await函数
4.3.1. await表达式
await 右侧的表达式一般为 promise 对象, 但也可以是其它的值
如果表达式是 promise 对象, await 返回的是 promise 成功的值
如果表达式是其它值, 直接将此值作为 await 的返回值
**4.3.2 ** 注意
await 必须写在 async 函数中, 但 async 函数中可以没有 await
如果 await 的 promise 失败了, 就会抛出异常, 需要通过 try…catch 捕获处理
<!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>
</head>
<body>
<script> // async函数返回结果是一个Promise async function main() {
let p = new Promise((resolve, reject) => {
resolve("ok"); }) // 1.如果await右侧是Promise,那么返回的是 promise 成功的值 let res = await p; console.log(res); // 2.如果await右侧不是Promise,那么直接将数据返回 let res2 = await "123"; console.log(res2); // 3.1.如果await右侧是Promise,但Promise执行失败,那么await会抛出异常,需要使用try-catch捕获 let p2 = new Promise((resolve, reject) => {
reject("ok"); }); try {
let res3 = await p2; } catch (error) {
console.log(error); } } main() </script>
</body>
</html>
4.4 async和await结合案例
// 要求读取当前文件夹下三个文件,并合并输出
// 回调函数形式实现
fs.readFile('./1.html',(err, data1)=>{
if(err) throw err;
fs.readFile('./1.html',(err, data2)=>{
if(err) throw err;
fs.readFile('./1.html',(err, data3)=>{
if(err) throw err;
console.log(data1+data2+data3);
})
})
})
// async和await结合实现
const fs = require('fs');
const util = require('util');
const minReadFile = util.promisify(fs.readFile);
async function main(){
try {
let data1 = await minReadFile("./1.html");
let data2 = await minReadFile("./2.html");
let data3 = await minReadFile("./3.html");
console.log(data1+data2+data3);
} catch (error) {
console.log(error);
}
}
4.5 async和await结合AJAX发送请求
<script>
function sendAJAX(url){
return new Promise((resolve, reject)=>{
})
}
let btn = document.querySelector("#btn");
btn.addEventListener('click', async function(){
let duanzi = await sendAJAX("https://api.apiopen.top/getJoke");
console.log(duanzi);
})
</script>
边栏推荐
- LeetCode高频题128. 最长连续序列,经常被互联网大厂面试考到
- Unity universal red dot system
- Software testing interview question: why should we carry out testing in a team?
- After learning the loop, I came across the problem of writing factorial of N, which caused a series of problems, including some common pitfalls for beginners, and how to simplify the code
- Forget the root password
- How to evaluate the effectiveness of R & D personnel? Software Engineer reports help you see everyone's contribution
- Five basic data structures of redis
- 【Star项目】小帽飞机大战(五)
- They are all talking about Devops. Do you really understand it?
- 忘记root密码
猜你喜欢
![[Taichi] draw a regular grid in Tai Chi](/img/48/14e825562afa3ffba96296799617f7.png)
[Taichi] draw a regular grid in Tai Chi

微信小程序实现动态横向步骤条的两种方式

go 学习01

网易云仿写

样本不均衡-入门0

一种比读写锁更快的锁,还不赶紧认识一下

Forget the root password

Talk to ye Yanxiu, an atlassian certification expert: where should Chinese users go when atlassian products enter the post server era?

go 学习02 基础知识

Fluorite network, difficult to be a "lone brave"
随机推荐
Gbase 8C database object size function (I)
华为APP UI自动化测试岗面试真题,真实面试经历。
ros2 launch文件常用模块
Record a production deadlock
What devices does devicexplorer OPC server support? This article has listed
【Star项目】小帽飞机大战(五)
A letter to the user of qubu drawing bed
In the era of great changes in material enterprises, SRM supplier procurement system helps enterprises build a digital benchmark for property procurement
Gbase 8C backup control function (I)
Gbase 8C annotation information function
软件测试面试题:为什要在一个团队中开展测试工作?
Gbase 8C backup control function (III)
Small bulk quantitative stock trading record | data is the source in the quantitative system, which teaches you to build a universal data source framework
Custom type: structure, enumeration, union
Data output - dynamic drawing
Machine learning how to achieve epidemic visualization -- epidemic data analysis and prediction practice
数据安全与隐私计算峰会-可证明安全:学习
A Tiger's Tale
机器学习如何做到疫情可视化——疫情数据分析与预测实战
Behind every piece of information you collect, you can't live without TA