当前位置:网站首页>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>
边栏推荐
- Golang's range
- Exe file running window embedding QT window
- Osgconv tool usage
- 如何应对数仓资源不足导致的核心任务延迟
- Mall management system of database application technology course design
- Markdown learning
- Osgearth topographic shading map drawing
- Unity learning notes
- Cesium service deployment, and import and display local 3dfiles data
- 【Rust 笔记】10-操作符重载
猜你喜欢

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

Redis data structure

Binary to decimal, decimal to binary

Introduction to Base64 coding

基于SSM的校园失物招领平台,源码,数据库脚本,项目导入运行视频教程,论文撰写教程

OpenGL learning notes

XPath实现XML文档的查询

Collection interface

Some understandings of 3dfiles

单调栈-503. 下一个更大元素 II
随机推荐
UE4 call DLL
Explain sizeof, strlen, pointer, array and other combination questions in detail
详解sizeof、strlen、指针和数组等组合题
Binary to decimal, decimal to binary
[audio and video] ijkplayer error code
matlab神經網絡所有傳遞函數(激活函數)公式詳解
Mysql容器化(1)Docker安装MySQL
Introduction to hexadecimal coding
Some understandings of 3dfiles
Kunlunbase meetup is waiting for you!
Downward compatibility and upward compatibility
Notes on understanding applets 2022/7/3
Simple demo of solving BP neural network by gradient descent method
C course design employee information management system
Redis cluster series 4
Markdown learning
[public key cryptography] ECC elliptic cryptosystem (implementing ElGamal encryption method)
如何应对数仓资源不足导致的核心任务延迟
Unity4.3.1 engine source code compilation process
Data analysis exercises