当前位置:网站首页>Promise from introduction to mastery (Chapter 4 async and await)
Promise from introduction to mastery (Chapter 4 async and await)
2022-07-28 02:13:00 【Ruoshui CJJ】
Promise From entry to mastery ( The first 4 Chapter async and await)
The first 4 Chapter async and await
4.1. mdn file
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 function
The return value of the function is promise object
promise The result of the object is determined by async The return value of the function execution determines ( and then Have the same characteristics )
<!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 The return result of the function is Promise async function main(){
// 1. If the return value is a non Promise, So back Promise Status as fulfilled, The result value is the returned result // return "123"; // 2. If the return value is a Promise, So back Promise Status as Promise The state of , The result value is Promise The result returned // return new Promise((resolve,reject)=>{
// reject("123"); // }); // 3. If the return value is an exception thrown , So back Promise Status as reject, The result value is the exception thrown throw "error"; } let result = main() console.log(result); </script>
</body>
</html>
4.3 await function
4.3.1. await expression
await The expression on the right is usually promise object , But it can be something else
If the expression is promise object , await The return is promise The value of success
If the expression is another value , Take this value directly as await The return value of
**4.3.2 ** Be careful
await Must be written in async Function , but async There can be no await
If await Of promise failed , Will throw an exception , Need to pass through try…catch Capture processing
<!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 The return result of the function is Promise async function main() {
let p = new Promise((resolve, reject) => {
resolve("ok"); }) // 1. If await The right side is Promise, So what's back is promise The value of success let res = await p; console.log(res); // 2. If await Right not Promise, Then return the data directly let res2 = await "123"; console.log(res2); // 3.1. If await The right side is Promise, but Promise Execution failure , that await It throws an exception , Need to use try-catch Capture 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 and await Combined with cases
// It is required to read three files under the current folder , And merge output
// The callback function is implemented in the form of
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 and await In combination with implementation
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 and await combination AJAX Send a request
<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>
边栏推荐
- Flex布局学习完成PC端
- uniapp 总结篇 (小程序)
- Common video resolution
- Likeshop takeout ordering system [100% open source, no encryption]
- Principle and implementation of focal loss
- 54: Chapter 5: develop admin management services: 7: face warehousing process; Face login process; The browser turns on the video debugging mode (so that the camera can also be turned on in the case o
- Domain Driven Design -- Terminology
- Leveraging the blue ocean of household appliances consumption with "digital channels", the dealer online system enables enterprises to further their business
- QGIS mapping: vector data mapping process and export
- Data output - image annotation and annotation
猜你喜欢
![[database data recovery] data recovery case of insufficient disk space of SQL Server database](/img/0e/908db40e1e8b7dd62e12558c1c6dc4.png)
[database data recovery] data recovery case of insufficient disk space of SQL Server database

产品解读丨MeterSphere UI测试模块的设计与分布式扩展

Execute add migration migration and report build failed

执行 Add-Migration 迁移时报 Build failed.

Starfish OS X metabell strategic cooperation, metauniverse business ecosystem further

go 学习02 基础知识

Codeforces Round #807 (Div. 2) A-C题解

Codeforces Round #810 (Div. 2)A~C题解

Enterprise operation and maintenance practice - using aliyun container image service to pull and build images of overseas GCR and quay warehouses

Unity universal red dot system
随机推荐
Skywalking distributed system application performance monitoring tool - medium
Packet capturing wizard netcapture app packet capturing tutorial "complete"
MySQL的pymysql操作
测试/开发程序员的级别“陷阱“,级别不是衡量单维度的能力......
Gbase 8C backup control function (III)
Behind every piece of information you collect, you can't live without TA
Common problem types and methods of mathematical univariate differential proof problems in postgraduate entrance examination
都在说DevOps,你真正了解它吗?
shell正则和元字符
Gbase 8C transaction ID and snapshot (VI)
【Star项目】小帽飞机大战(五)
Zkrollup learning materials summary
Starfish Os X MetaBell战略合作,元宇宙商业生态更进一步
Sample imbalance - entry 0
IT这个岗位,人才缺口百万,薪资水涨船高,上不封顶
Software testing interview question: what do you think is the key to good test case design?
Flex布局—固定定位+流式布局—主轴对齐—侧轴对齐—伸缩比
数据输出-图片注释、标注
Interviewer: are you sure redis is a single threaded process?
Uniapp summary (applet)