当前位置:网站首页>Es8 async and await learning notes
Es8 async and await learning notes
2022-07-03 08:40:00 【Rain shallow listen to the wind sing】
List of articles
1 Concept
- async and await
async and await The combination of the two syntax can make asynchronous code like synchronous code - async function
2.1. async The return value of the function is promise object ,
2.2. promise The result of the object is determined by async The return value of the function execution determines - await expression
3.1await Must be written in async Function
3.2await The expression on the right is usually promise object
3.3await The return is promise The value of success
3.4. await Of promise failed , Will throw an exception , Need to pass through try…catch Capture processing
2async function
The result returned is not a Promise Object of type , The result returned is success Promise object 

Throw an error , The result returned is a failed Promise

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>async function </title>
</head>
<body>
<script>
//async function
async function fn(){
// Returns a string
// return ' Silicon Valley ';
// The result returned is not a Promise Object of type , The result returned is success Promise object
// return;
// Throw an error , The result returned is a failed Promise
// throw new Error(' Error !');
// If the returned result is a Promise object
return new Promise((resolve, reject)=>{
resolve(' Success data ');
// reject(" The mistake of failure ");
});
}
const result = fn();
// call then Method
result.then(value => {
console.log(value);
}, reason => {
console.warn(reason);
})
</script>
</body>
</html>
and promise The effect is the same , return reject Coming out is reason Callback
# await

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>await</title>
</head>
<body>
<script>
// establish promise object
const p = new Promise((resolve, reject) => {
// resolve(" User data ");
reject(" Failed !");
})
// await Put it on async Function .
async function main() {
try {
let result = await p;
//
console.log(result);
} catch (e) {
console.log(e);
}
}
// Call function
main();
</script>
</body>
</html>
async and await Combined read file
//1. introduce fs modular
const fs = require("fs");
// Read 『 For learning 』
function readWeiXue() {
return new Promise((resolve, reject) => {
fs.readFile("./resources/ For learning .md", (err, data) => {
// If you fail
if (err) reject(err);
// If it works
resolve(data);
})
})
}
function readChaYangShi() {
return new Promise((resolve, reject) => {
fs.readFile("./resources/ Rice transplanting Poetry .md", (err, data) => {
// If you fail
if (err) reject(err);
// If it works
resolve(data);
})
})
}
function readGuanShu() {
return new Promise((resolve, reject) => {
fs.readFile("./resources/ I have a feeling of reading .md", (err, data) => {
// If you fail
if (err) reject(err);
// If it works
resolve(data);
})
})
}
// Make a statement async function
async function main(){
// Get content for learning
let weixue = await readWeiXue();
// Get the content of rice transplanting poem
let chayang = await readChaYangShi();
// Get a sense of reading
let guanshu = await readGuanShu();
console.log(weixue.toString());
console.log(chayang.toString());
console.log(guanshu.toString());
}
main();

async and await encapsulation ajax request
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title> send out AJAX request </title>
</head>
<body>
<script>
// send out AJAX request , The result is Promise object
function sendAJAX(url) {
return new Promise((resolve, reject) => {
//1. Create objects
const x = new XMLHttpRequest();
//2. initialization
x.open('GET', url);
//3. send out
x.send();
//4. Event binding
x.onreadystatechange = function () {
if (x.readyState === 4) {
if (x.status >= 200 && x.status < 300) {
// It's a success
resolve(x.response);
}else{
// If you fail
reject(x.status);
}
}
}
})
}
//promise then Method test
// sendAJAX("https://api.apiopen.top/getJoke").then(value=>{
// console.log(value);
// }, reason=>{})
// async And await test axios
async function main(){
// send out AJAX request
let result = await sendAJAX("https://api.apiopen.top/getJoke");
// The test again
let tianqi = await sendAJAX('https://www.tianqiapi.com/api/?version=v1&city=%E5%8C%97%E4%BA%AC&appid=23941491&appsecret=TXoD5e8P')
console.log(tianqi);
}
main();
</script>
</body>
</html>
边栏推荐
- UE4 source code reading_ Bone model and animation system_ Animation compression
- 【Rust 笔记】08-枚举与模式
- [redis] redis persistent RDB vs AOF (source code)
- LinkedList set
- 梯度下降法求解BP神经网络的简单Demo
- [MySQL] MySQL Performance Optimization Practice: introduction of database lock and index search principle
- 了解小程序的笔记 2022/7/3
- 【云原生】微服务之Feign的介绍与使用
- Osgconv tool usage
- [K & R] Chinese Second Edition personal questions Chapter1
猜你喜欢

XPath实现XML文档的查询

Graphics_ Games101/202 learning notes

Thymeleaf 404 reports an error: there was unexpected error (type=not found, status=404)

Jupyter remote server configuration and server startup

Monotonic stack -84 The largest rectangle in the histogram

Mxone Pro adaptive 2.0 film and television template watermelon video theme apple cmsv10 template

第一个Servlet

详解sizeof、strlen、指针和数组等组合题

Unity editor expansion - controls, layouts

Chocolate installation
随机推荐
Display terrain database on osgearth ball
Un système de gestion de centre commercial pour la conception de cours de technologie d'application de base de données
【Rust 笔记】07-结构体
基于SSM的校园失物招领平台,源码,数据库脚本,项目导入运行视频教程,论文撰写教程
matlab神經網絡所有傳遞函數(激活函數)公式詳解
Notes on understanding applets 2022/7/3
[rust notes] 08 enumeration and mode
OpenGL learning notes
Unity editor expansion - draw lines
【Rust笔记】06-包和模块
Location of package cache downloaded by unity packagemanager
请求参数的发送和接收
[rust notes] 02 ownership
第一个Servlet
图像处理8-CNN图像分类
KunlunBase MeetUP 等您来!
Unity editor expansion - scrolling list
Unity editor expansion - the framework and context of unity imgui
Campus lost and found platform based on SSM, source code, database script, project import and operation video tutorial, Thesis Writing Tutorial
Advanced OSG collision detection