当前位置:网站首页>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
边栏推荐
- 44. Concurrent programming theory
- Global and Chinese markets of lithium chloride 2022-2028: Research Report on technology, participants, trends, market size and share
- Reinforcement learning - learning notes 1 | basic concepts
- How to modify the network IP addresses of mobile phones and computers?
- 2022 melting welding and thermal cutting examination materials and free melting welding and thermal cutting examination questions
- Producer consumer mode (multithreading, use of shared resources)
- JVM JNI and PVM pybind11 mass data transmission and optimization
- String and+
- 浅析 Ref-NeRF
- Sparse matrix (triple) creation, transpose, traversal, addition, subtraction, multiplication. C implementation
猜你喜欢
Interval product of zhinai sauce (prefix product + inverse element)
How to do Taobao full screen rotation code? Taobao rotation tmall full screen rotation code
jvm jni 及 pvm pybind11 大批量数据传输及优化
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
《ActBERT》百度&悉尼科技大学提出ActBERT,学习全局局部视频文本表示,在五个视频-文本任务中有效!...
Use nodejs+express+mongodb to complete the data persistence project (with modified source code)
TLS environment construction and plaintext analysis
[Tang Laoshi] C -- encapsulation: member variables and access modifiers
Explore the internal mechanism of modern browsers (I) (original translation)
随机推荐
2.5 conversion of different data types (2)
Global and Chinese market of two in one notebook computers 2022-2028: Research Report on technology, participants, trends, market size and share
浅议.NET遗留应用改造
MySQL dump - exclude some table data - MySQL dump - exclude some table data
Initialization and instantiation
The 29th day of force deduction (DP topic)
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
浅议.NET遗留应用改造
First knowledge of database
Wargames study notes -- Leviathan
Global and Chinese market of speed limiter 2022-2028: Research Report on technology, participants, trends, market size and share
Global and Chinese market of high purity copper foil 2022-2028: Research Report on technology, participants, trends, market size and share
Global and Chinese market of rubidium standard 2022-2028: Research Report on technology, participants, trends, market size and share
Kubernetes abnormal communication network fault solution ideas
thrift go
2.7 format output of values
2.2 integer
Exercises of function recursion
JVM JNI and PVM pybind11 mass data transmission and optimization
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%