当前位置:网站首页>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>
边栏推荐
猜你喜欢
注解简化配置与启动时加载
Markdown learning
[concurrent programming] explicit lock and AQS
Servlet的生命周期
Gradle's method of dynamically modifying APK package name
Message queue for interprocess communication
Introduction to Base64 coding
100 GIS practical application cases (78) - Multi compliance database design and data warehousing
php-fpm软件的安装+openresty高速缓存搭建
Visual Studio (VS) shortcut keys
随机推荐
Graphics_ Learnopongl learning notes
了解小程序的笔记 2022/7/3
Transmit pictures with Base64 encoding
[RPC] RPC remote procedure call
OpenGL learning notes
基于SSM的校园失物招领平台,源码,数据库脚本,项目导入运行视频教程,论文撰写教程
Monotonic stack -503 Next bigger Element II
Cesium for unreal quick start - simple scenario configuration
详解sizeof、strlen、指针和数组等组合题
[cloud native] introduction and use of feign of microservices
Cesium service deployment, and import and display local 3dfiles data
C course design employee information management system
Introduction to Base64 coding
Binary to decimal, decimal to binary
单调栈-84. 柱状图中最大的矩形
[rust notes] 07 structure
Use of ue5 QRcode plug-in
[public key cryptography] ECC elliptic cryptosystem (implementing ElGamal encryption method)
Golang's range
[rust notes] 05 error handling