当前位置:网站首页>async await
async await
2022-06-11 01:07:00 【Front lvxiaobu】
background
For a long time , Front end engineers have to rely on callbacks to handle asynchronous code . The result of using callbacks is , The code gets tangled , Not easy to understand and maintain , thankfully Promise brought .then(), Keep the code in order , Easy to manage . So we use a lot of , Instead of the original callback method . But there is no way to block the current execution process until promise complete .JS Inside , We can't just wait promise complete , The only way to plan ahead promise The way to execute logic after completion is through then Additional callback functions . Now with ES7 in async await An increase in , The interface can get data asynchronously in order , Use more semantics , Handle callbacks in a maintainable way .
Introduce
async await Is a long-awaited JavaScript characteristic , Let's better understand the use of asynchronous functions . It is based on Promises On , And with all existing based on Promise Of API compatible .
async
grammar :async function foo(){…}
effect : Declare an asynchronous function
- Automatically convert regular functions to Promise, The return value is also a Promise object
- Only async The asynchronous operation inside the function is finished , Will execute then Callback function specified by method
- Asynchronous functions can be used internally await
await
grammar :var result = await someAsyncCall()
effect : Pause asynchronous function execution
- Put in Promise Before you call ,await Force other code to wait , until Promise Complete and return results
- Only with Promise Use it together , Not applicable with callback
- Only in async Function internal use
async Function can be regarded as a function wrapped by multiple asynchronous operations Promise object , and await Command is internal then Grammar sugar of command .
Use
async Use
// Function declaration
async function foo() {
}
// Function expression
let foo = async function() {
}
// Object method
const obj = {
async foo() {
}
}
console.log(obj.foo()) // Promise object , The value is undefined
obj.foo().then(() => console.log(1)) // 1
// Arrow function
let foo = async () => {
}
await Use
await The rules of use are relatively simple , It needs to be followed by Promise object , If not, it will be converted to Promise object . Just one of them Promise The object becomes rejected state , So the whole async Functions interrupt operations . If the state is fulfilled, Then its return value will become then The parameters inside , as follows :
// await
async function foo() {
return await 123
}
foo().then(res => {
console.log(res) }) // 123
// class Methods
class Storage {
constructor() {
this.cachePromise = caches.open('avatars')
}
async getAvatar(name) {
const cache = await this.cachePromise
return cache.match(`/avatars/${
name}.jpg`)
}
}
const storage = new Storage()
storage.getAvatar(1).then((res) => {
console.log(res)}) // undefined
- because await hinder promise The result of the run might be rejected, It's better to await Put in try/catch in
- await Asynchronous operation after , If there is no dependency on each other, it is better to trigger at the same time
- await Only in async Among functions , If in a normal function , Will report a mistake
Use scenarios
1、 Make multiple independent requests at the same time , Unsuitable for use async await
async function getDatas() {
let A = await getValueA()
let B = await getValueB()
let C = await getValueC()
return A + B + C
}
Above we A need 2s,B need 4s,C need 3s, If we make a request like this , There is a relationship of mutual dependence ,c etc. b After execution ,b etc. a After execution , From the beginning to the end, we need (2+3+4)9s.
At this point we need to use Promise.all() Execute asynchronous calls in parallel , Instead of executing one by one , As shown below :
async function getDatas() {
let results = await Promise.all([getValueA, getValueB, getValueC])
return results.reduce((total, item) => total + item)
}
This will save us a lot of time , From the original 9s Reduce to 4s.
2、 Make multiple interdependent requests , Suitable for use async await
A page for submitting forms , There's a name in it 、 Gender and other information , One of them is the mobile phone verification code , We have to wait for the mobile phone verification code interface to pass , To issue subsequent request operations , At this time, the interfaces depend on each other ,async await There is a place for use , So that asynchronous requests can be executed sequentially .
Not used async await Writing , We have to use .then() The way , After the first interface that requests the verification code has a return value , In order to execute the following Promise, And you need a then Output results , as follows :
// Request for mobile phone verification code
let callPromise1 = fetch('http://api/getCode')
callPromise1.then(res => res.json())
.then(json => {
// Perform subsequent operations on the return value of the verification code , Such as submitting forms
let callPromise2 = fetch('http://api/postForm')
return callPromise2
})
.then(res => res.json())
.then(json => {
// Output the results after execution
console.log(json.resCode)
})
.catch(err => console.log(err))
While using async await The way to write is as follows , We put the logic in one async In the function . So that we can directly Promise Object use await 了 , It avoids writing then Callback . Finally we call this async function , Then use the returned... In the normal way promise:
// Request to submit form
async function postForm() {
try {
// Whether the mobile phone verification code passes , Get the returned json
let res1 = await fetch('http://api/getCode')
let json1 = await res1.json()
let json2
// Judge the returned data of the first interface , If the condition is met, the second interface is requested , And return the data
if (json1.resCode === 200) {
const res2 = await fetch('http://api/postForm')
json2 = await res2.json()
}
return json2
} catch (err) {
console.log(err)
}
}
// perform postForm
postForm().then(json => console.log(json))
summary
async await Let's use a small amount of code Promise, We can put the processing logic of some dependent callback functions in async Inside , And then in Africa async The area used by , This can reduce then perhaps catch Callback .
边栏推荐
- CentOS实战部署redis
- 阻塞隊列 — DelayedWorkQueue源碼分析
- 最好的创意鼓工具:Groove Agent 5
- 负载均衡策略图文详解
- 【ROS入门教程】---- 03 ROS工作空间与功能包
- [introduction to ROS] - 03 basic concepts and instructions of ROS
- Why web development with golang
- Why is the digital transformation of small and medium-sized enterprises so difficult?
- 中小企业数字化转型为什么这么难?
- MESI cache consistency protocol for concurrent programming
猜你喜欢

Random points in non overlapping rectangles

Block queue - delayedworkqueue Source Analysis

亿级搜索系统(优酷视频搜索)的基石,如何保障实时数据质量?v2020
WSL automatically updates the IP hosts file

手把手教你前后分离架构(五) 系统身份验证实现

UUID quick explanation

Google搜索为什么不能无限分页?

87.(leaflet之家)leaflet军事标绘-直线箭头修改

About log traffic monitoring and early warning small project | flag log monitoring script

招聘 | 南京 | TRIOSTUDIO 三厘社 – 室内设计师 / 施工图深化设计师 / 装置/产品设计师 / 实习生等
随机推荐
CentOS实战部署redis
Embedded learning materials and project summary
Summary of pytorch classification problems
记录oracle的几个参数 db_files,Cursor_sharing ,open_cursor
[论文阅读] FixMatch: Simplifying Semi-Supervised Learning with Consistency and Confidence
compiler explorer
Slam Kalman filter & nonlinear optimization
Dynamic programming classical topic triangle shortest path
Can I buy annuity insurance? Is annuity insurance safe?
Idea setting background picture (simple)
CentOS actual deployment redis
[论文阅读] TGANet: Text-guided attention for improved polyp segmentation
Synchronized keyword for concurrent programming
The best creative drum tool: groove agent 5
The JVM determines whether an object can be recycled
OTA升级
How to guarantee the quality of real-time data, the cornerstone of the 100 million level search system (Youku Video Search)? v2020
CentOS7 实战部署MySQL8(二进制方式)
dma_ buf_ export
NVIDIA Jetson之PWM风扇自定义控制