当前位置:网站首页>[ecmascript6] async and await
[ecmascript6] async and await
2022-07-28 14:22:00 【Willard Leozi】
async function
async The function returns a Promise object , The state of the object depends on the return value of the function , If the function returns
Not Promise Object or return success Promise, Then this function returns Promise Object state
For success , If the function returns a failed Promise Object or throw an error , Then this function returns Promise
The object status is failed
async function fn() {
return new Promise((resolve, reject) => {
resolve(' Request successful data ')
})
}
const result = fn()
result.then(value => {
console.log(value) // Request successful data
}, error => {
console.warn(error)
})
await expression
const p = new Promise((resolve, reject) => {
resolve(' Success data ')
})
// await To put async Function , Followed by a Promise object
async function fn() {
// await The result returned is after Promise The successful value of the object ( Pay attention to one. Promise Object has two properties , One is state , The other is the value )
// If later Promise The state of the object is failed , An error will be thrown
let result = await p
console.log(result) // Success data
}
fn()
const p1 = new Promise((resolve, reject) => {
reject(' Failure information ')
})
// await To put async Function , Followed by a Promise object
async function fn1() {
try {
// If later Promise The state of the object is failed , An error will be thrown , Need to use try...catch Capture
let result = await p1
} catch(e) {
console.log(e) // Failure information
}
}
fn1()
async And await Combined with reading the contents of the file

const fs = require('fs')
function readFile1() {
return new Promise((resolve, reject) => {
fs.readFile('./file1.md', (err, data) => {
if(err) reject(err)
resolve(data)
})
})
}
function readFile2() {
return new Promise((resolve, reject) => {
fs.readFile('./file2.md', (err, data) => {
if(err) reject(err)
resolve(data)
})
})
}
function readFile3() {
return new Promise((resolve, reject) => {
fs.readFile('./file3.md', (err, data) => {
if(err) reject(err)
resolve(data)
})
})
}
async function readFiles() {
let fileData1 = await readFile1()
let fileData2 = await readFile2()
let fileData3 = await readFile3()
console.log(fileData1.toString() + '\r\n' + fileData2.toString() + '\r\n' + fileData3.toString())
}
readFiles()

async And await Combined transmission Ajax request
// send out Ajax request , The result is Promise object
function sendAjax(url) {
return new Promise((resolve, reject) => {
// 1. Create objects
const xhr = new XMLHttpRequest()
// 2. initialization
xhr.open('GET', url)
// 3. send out
xhr.send()
// 4. The binding event , Process response results
xhr.onreadystatechange = function() {
if(xhr.readyState === 4) {
if(xhr.status >= 200 && xhr.status < 300) {
resolve(xhr.response)
}else {
reject(xhr.status)
}
}
}
})
}
// Assume that the test interface is :https://api.apiopen.top/getJoke
// 1. adopt Promise then Method to test
sendAjax('https://api.apiopen.top/getJoke').then(value => {
console.log(value)
}, error => {
console.log(error)
})
// 2. adopt async await Method to test
async function main() {
let result = await sendAjax('https://api.apiopen.top/getJoke')
console.log(result) // result by sendAjax return Promise The value of success , That is, the required data information
}
main()
// notes : vue Medium axios The return value is also a Promise object , It can be very good and async await Use a combination of
边栏推荐
- [basic course of flight control development 7] crazy shell · open source formation UAV SPI (barometer data acquisition)
- [ecmascript6] set and map
- [lvgl events] Application of events on different components (I)
- HCIP第十天
- Open source project - taier1.2 release, new workflow, tenant binding simplification and other functions
- Security assurance is based on software life cycle -psp application
- 阿里、京东、抖音:把云推向产业心脏
- JMeter installation tutorial and login add token
- 【Utils】JsonUtil
- [lvgl events] event code
猜你喜欢

QQ robot configuration record based on nonebot2

Security assurance is based on software life cycle -psp application

Development and definition of software testing
![[ecmascript6] set and map](/img/64/dd6ffc5f0faf881b990e609cf62343.png)
[ecmascript6] set and map

LeetCode 0142.环形链表 II

Clickhouse分布式集群搭建

修订版 | 目标检测:速度和准确性比较(Faster R-CNN,R-FCN,SSD,FPN,RetinaNet和YOLOv3)...

How to effectively conduct the review meeting (Part 1)?

如何有效进行回顾会议(上)?

走进音视频的世界——FLV视频封装格式
随机推荐
Clickhouse distributed cluster construction
How did Dongguan Huawei cloud data center become a new model of green data center?
HCIP第十二天
离散对数问题(DLP) && Diffie-Hellman问题(DHP)
Open source project - taier1.2 release, new workflow, tenant binding simplification and other functions
Leetcode 1331. array sequence number conversion
Development and definition of software testing
[lvgl events] Application of events on different components (I)
【Utils】JsonUtil
How to write test cases in software testing technology
Introduction to database system (5th Edition) supplementary exercises - Chapter 1 Introduction
Xcode编写SwiftUI代码时一个编译通过但导致预览(Preview)崩溃的小陷阱
PowerDesigner creates a database model (conceptual model example)
Detailed explanation of common commands of vim (VIM use tutorial)
Foundation of deep learning ---- GNN spectral domain and airspace (continuous improvement, update and accumulation)
作为一个程序员,如何高效的管理时间?
Websocket chat
Three methods to disassemble the rotation array
用友BIP CRM新品发布,赋能大中型企业营销增长
Thoroughly master binary search