当前位置:网站首页>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>
边栏推荐
- redis集群系列四
- How to deal with the core task delay caused by insufficient data warehouse resources
- Huawei interview summary during the epidemic
- Detailed explanation of all transfer function (activation function) formulas of MATLAB neural network
- Development material set
- UE4 source code reading_ Bone model and animation system_ Animation compression
- UE4 call DLL
- Notes on understanding applets 2022/7/3
- Binary to decimal, decimal to binary
- [rust notes] 11 practical features
猜你喜欢

Creation of osgearth earth files to the earth ------ osgearth rendering engine series (1)

Redis data structure

Final review of Database Principles

Visual Studio (VS) shortcut keys

Use of ue5 QRcode plug-in

注解简化配置与启动时加载

数据库原理期末复习

Un système de gestion de centre commercial pour la conception de cours de technologie d'application de base de données

Unity editor expansion - draw lines

Servlet的生命周期
随机推荐
Unity editor expansion - window, sub window, menu, right-click menu (context menu)
22-06-27 西安 redis(01) 安装redis、redis5种常见数据类型的命令
Detailed explanation of all transfer function (activation function) formulas of MATLAB neural network
[rust note] 10 operator overloading
Markdown directory generation
二进制转十进制,十进制转二进制
Use of ue5 QRcode plug-in
[MySQL] MySQL Performance Optimization Practice: introduction of database lock and index search principle
[concurrent programming] atomic operation CAS
[updating] wechat applet learning notes_ three
Unity multi open script
如何应对数仓资源不足导致的核心任务延迟
Unity editor expansion - the framework and context of unity imgui
producer consumer problem
[rust notes] 06 package and module
How does unity fixedupdate call at a fixed frame rate
XPath实现XML文档的查询
[rust notes] 05 error handling
Redis cluster series 4
[rust notes] 02 ownership