当前位置:网站首页>Sort out several network request methods of JS -- get rid of callback hell
Sort out several network request methods of JS -- get rid of callback hell
2022-07-03 20:40:00 【Raring_ Ringtail】
I haven't learned front-end systematically , When writing the front end, it's ok if it's just a single network request , use fetch、axios Or use it directly XMLHttpRequest It's not complicated to write .
But if multiple requests pull data in sequence, it will kill me , I can only write the simplest callback function , Like the following code :
const requestOptions = {
method: 'GET',
redirect: 'follow'
};
fetch('https://xxx.yyy.com/api/zzz/', requestOptions)
.then(response => response.text())
.then(result => {
const data = JSON.parse(result)
fetch('https://xxx.yyy.com/api/aaa/'+data.id, requestOptions)
.then(response => response.text())
.then(result => {
const data = JSON.parse(result)
})
.catch(error => console.log('error', error));
})
.catch(error => console.log('error', error));
Suppose I need two steps to get a data , If you follow https://xxx.yyy.com/api/zzz/ Get a data object data, After through data.id Get the serial number of the data I want to get , Finally, send another request to get the desired data .
The callback method is similar to the above , It's too complicated , And it's easy to make mistakes , And once the logic is complex, it's hard to change .
Take some time to learn this knowledge today , Get out of hell
One 、XMLHttpRequest
adopt XMLHttpRequest The routine of creating network requests for objects is as follows :
// Hypothetical visit http://localhost:3000/user return json object {"name":"Jiangda"}
const xhr = new XMLHttpRequest();
const url = 'http://localhost:3000/user'
xhr.onreadystatechange = function(){
if (this.readyState == 4 && this.status == 200){
let json=JSON.parse(xhr.responseText)
let name=json.name
console.log(name)
}
}
xhr.open('GET',url)
xhr.send()
First create a XMLHttpRequest object xhr, then xhr.onreadystagechange monitor “ State change ” event , after xhr.open Initialization request , Last xhr.send Send a request .
After the request is sent , When the browser receives a response, it will enter xhr.onreadystagechange In the callback function of , First if (this.readyStage == 4 && this.status == 200) Judge readyStage Is it right? 4, During the entire request process ,xhr.onreadystagechange Will trigger four times , Every time readyStage Will be on the , from 1 Until 4, Only in the final stage, that is readyStage by 4 Then we can get the final response data , At the same time, according to status Judge whether the response status code is normal , Usually the response code is 2 The beginning indicates that the request has not encountered a problem , Finally, it will be displayed on the console Jiangda.
It can be seen that , adopt XMLHttpRequest To handle the request , Writing callback functions is troublesome .
Two 、Promise
If an event depends on the return result of another event , Then using callbacks can complicate the code .Promise Object provides a mode for checking the failure or success of an operation . If it works , Will return to another Promise. This makes the writing of callback more standardized .
Promise The treatment routine is as follows :
const promise = new Promise((resolve,reject)=>{
let condition = true;
if (condition) {
resolve("ok")
} else {
reject("failed")
}
}).then( msg => console.log(msg))
.catch( err => console.error(err))
.finally( _ =>console.log("finally"))
The above code concatenates the whole process , First create a Promise object , Its constructor receives a function , The first parameter of the function is the function to be executed when there is no error resolve, The second parameter is the function to be executed after the error reject.
My understanding is that resolve and reject It's just a proxy ,resolve After successful Anaphora then The callback function inside ,reject After the failure of pronoun catch Callback function executed in . final finally It will be executed regardless of success or failure , It can be used to do some finishing work .
be based on Promise Your network request can be made with axios Libraries and browsers come with fetch Realization .
axios The routine of library creation request is as follows :
import axios from 'axios'
const url = 'http://xxx.yyy.com/'
axios.get(url)
.then(data => console.log(data))
.catch(err => console.error(err))
I prefer to use it fetch, It doesn't need to import libraries ,fetch How and how to create the request axios similar , If you've shown it at the beginning, don't repeat it .
although Promise Simplify the writing method of callback function , But still not out of hell , If multiple requests are strung together, it will be like what I wrote at the beginning , stay then Create a new Promise, Eventually it becomes Promise hell
3、 ... and 、async/await
async/await Can be simplified Promise Writing , Make the functions in the code asynchronous, but the execution order is synchronous , And the writing of code is similar to that of synchronization , Easy to understand .
Take it directly MDN(https://developer.mozilla.org/zh-CN/docs/Learn/JavaScript/Asynchronous/Async_await) Let's illustrate with the example on :
Direct use fetch get data :
fetch('coffee.jpg')
.then(response => response.blob())
.then(myBlob => {
let objectURL = URL.createObjectURL(myBlob);
let image = document.createElement('img');
image.src = objectURL;
document.body.appendChild(image);
})
.catch(e => {
console.log('There has been a problem with your fetch operation: ' + e.message);
});
async/await After rewriting :
async function myFetch() {
let response = await fetch('coffee.jpg');
let myBlob = await response.blob();
let objectURL = URL.createObjectURL(myBlob);
let image = document.createElement('img');
image.src = objectURL;
document.body.appendChild(image);
}
myFetch()
.catch(e => {
console.log('There has been a problem with your fetch operation: ' + e.message);
});
Is the rewritten code clear , Not so much then Followed , In this way, if there is a series of network requests, you don't have to be afraid
When async When placed before the declaration of a function , This function is an asynchronous function , Calling this function will return a Promise.
await Used to wait for a Promise object , It can only be used in asynchronous functions ,await The expression pauses the execution of the current asynchronous function , wait for Promise Processing is complete .
Welcome to my WeChat official account. Notes on Jiangda
边栏推荐
- 强基计划 数学相关书籍 推荐
- Viewing Chinese science and technology from the Winter Olympics (II): when snowmaking breakthrough is in progress
- The global industrial design revenue in 2021 was about $44360 million, and it is expected to reach $62720 million in 2028. From 2022 to 2028, the CAGR was 5.5%
- Initialization and instantiation
- Discussion Net legacy application transformation
- In 2021, the global revenue of syphilis rapid detection kits was about US $608.1 million, and it is expected to reach US $712.9 million in 2028
- AST (Abstract Syntax Tree)
- App compliance
- Do you really know how old you are?
- Strange way of expressing integers (expanding Chinese remainder theorem)
猜你喜欢
![AI enhanced safety monitoring project [with detailed code]](/img/a9/cb93f349229e86cbb05ad196ae9553.jpg)
AI enhanced safety monitoring project [with detailed code]

Operate BOM objects (key)

In 2021, the global revenue of thick film resistors was about $1537.3 million, and it is expected to reach $2118.7 million in 2028

19、 MySQL -- SQL statements and queries
![[effective Objective-C] - block and grand central distribution](/img/09/22b979b97ea13d649b4b904637b79f.jpg)
[effective Objective-C] - block and grand central distribution

thrift go

Recommendation of books related to strong foundation program mathematics

An old programmer gave it to college students

1.4 learn more about functions

SQL injection - Fundamentals of SQL database operation
随机推荐
【愚公系列】2022年7月 Go教学课程 002-Go语言环境安装
11-grom-v2-05-initialization
Sparse matrix (triple) creation, transpose, traversal, addition, subtraction, multiplication. C implementation
Viewing Chinese science and technology from the Winter Olympics (II): when snowmaking breakthrough is in progress
Operate BOM objects (key)
Set, weakset, map, weakmap in ES6
Change deepin to Alibaba image source
Interval product of zhinai sauce (prefix product + inverse element)
2.3 other data types
浅析 Ref-NeRF
强化學習-學習筆記1 | 基礎概念
Global and Chinese market of full authority digital engine control (FADEC) 2022-2028: Research Report on technology, participants, trends, market size and share
XAI+网络安全?布兰登大学等最新《可解释人工智能在网络安全应用》综述,33页pdf阐述其现状、挑战、开放问题和未来方向
TLS environment construction and plaintext analysis
Wargames study notes -- Leviathan
Global and Chinese markets of active matrix LCD 2022-2028: Research Report on technology, participants, trends, market size and share
如临现场的视觉感染力,NBA决赛直播还能这样看?
Qt6 QML Book/Qt Quick 3D/基础知识
SQL injection - Fundamentals of SQL database operation
C 10 new feature [caller parameter expression] solves my confusion seven years ago