当前位置:网站首页>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>
边栏推荐
猜你喜欢

Redis design specification

Redis设计规范

Cloud native enthusiast weekly: the evolution of Prometheus architecture

Flex布局—固定定位+流式布局—主轴对齐—侧轴对齐—伸缩比

JS what situations can't use json Parse, json.stringify deep copy and a better deep copy method

Vxe Table/Grid 单元格分组合并

QGIS制图:矢量数据制图流程及导出

二叉树的遍历和性质

Unity universal red dot system

ArcGIS: loading historical remote sensing images
随机推荐
JS what situations can't use json Parse, json.stringify deep copy and a better deep copy method
Codeworks round 807 (Div. 2) a-c problem solution
Cloud native enthusiast weekly: the evolution of Prometheus architecture
Go learn 02 basic knowledge
[database data recovery] data recovery case of insufficient disk space of SQL Server database
Unity universal red dot system
Small bulk quantitative stock trading record | data is the source in the quantitative system, which teaches you to build a universal data source framework
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
The petrochemical industry is facing the tide of rising prices, and the digital dealer distribution system platform enables dealers and stores
What devices does devicexplorer OPC server support? This article has listed
Gbase 8C transaction ID and snapshot (V)
Use of classes in typescript
Data security and privacy computing summit - provable security: Learning
MPLS tunnel experiment
Gbase 8C backup control function (II)
Typescript中类的使用
Software test interview questions: common post data submission methods
Synchronized details
Unittest单元测试框架全栈知识
synchronized详解