当前位置:网站首页>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
边栏推荐
- Change deepin to Alibaba image source
- Micro service knowledge sorting - asynchronous communication technology
- How to do Taobao full screen rotation code? Taobao rotation tmall full screen rotation code
- Global and Chinese markets of lithium chloride 2022-2028: Research Report on technology, participants, trends, market size and share
- Research Report on the overall scale, major manufacturers, major regions, products and application segmentation of rotary tablet presses in the global market in 2022
- Get log4net log file in C - get log4net log file in C
- 2022 high voltage electrician examination and high voltage electrician reexamination examination
- Assign the CMD command execution result to a variable
- Global and Chinese market of charity software 2022-2028: Research Report on technology, participants, trends, market size and share
- 2.5 conversion of different data types (2)
猜你喜欢
MySQL master-slave synchronization principle
Gee calculated area
MDM mass data synchronization test verification
2.2 integer
Qtablewidget control of QT
一台服务器最大并发 tcp 连接数多少?65535?
Etcd 基于Raft的一致性保证
From the behind the scenes arena of the ice and snow event, see how digital builders can ensure large-scale events
Sightseeing - statistics of the number of shortest paths + state transfer + secondary small paths
jvm jni 及 pvm pybind11 大批量数据传输及优化
随机推荐
2.4 conversion of different data types
Sword finger offer 30 Stack containing min function
Set, weakset, map, weakmap in ES6
设计电商秒杀系统
1.4 learn more about functions
Based on laravel 5.5\5.6\5 X solution to the failure of installing laravel ide helper
Node MySQL serialize cannot rollback transactions
Plan for the first half of 2022 -- pass the PMP Exam
2.3 other data types
AcWing 1460. Where am i?
Discussion Net legacy application transformation
Test panghu was teaching you how to use the technical code to flirt with girls online on Valentine's Day 520
Initialization and instantiation
Popularize the basics of IP routing
Micro service knowledge sorting - asynchronous communication technology
Global and Chinese market of full authority digital engine control (FADEC) 2022-2028: Research Report on technology, participants, trends, market size and share
浅析 Ref-NeRF
How to handle wechat circle of friends marketing activities and share production and release skills
Machine learning support vector machine SVM
Basic command of IP address configuration ---ip V4