In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article will explain in detail the ways in which JS can achieve network requests. The editor thinks it is very practical, so I share it with you for reference. I hope you can get something after reading this article.
Background
In order to cope with more and more testing requirements and reduce repetitive work, youdao Intelligent hardware Test Group has developed a series of test efficiency tools based on electron.
With the rapid development and iteration of the tool, more and more nested callback functions appear in the code, and the tool is more and more likely to crash. In order to solve these problems, we use async/await to reconstruct these callback functions, which reduces the amount of code and greatly improves the readability and understandability of the code.
This paper introduces three kinds of asynchronous network request writing methods based on XMLHttpRequest, Promise and async/await, in which async/await allows us to write asynchronous programs in a way similar to synchronization and get rid of tedious callback functions.
Preface
In js, if only initiating a single network request is not complicated, using fetch, axios or directly using XMLHttpRequest can meet the requirements.
However, if multiple requests pull data sequentially, it is troublesome to write, because the network requests in js are all asynchronous, and if you want to execute them sequentially, the most common way to write them is to initiate the next request in the callback function, such as the following code:
Const requestOptions = {method: 'GET', redirect:' follow'} Fetch ('https://xxx.yyy.com/api/zzz/', requestOptions). Then (response = > response.json ()). Then (data = > {fetch (' https://xxx.yyy.com/api/aaa/'+data.id,) RequestOptions) .then (response = > response.json ()) .then (data = > {console.log (data)}) .catch (error = > console.error ('error', error)) ) .catch (error = > console.error ('error', error))
Suppose I need to take two steps to get a piece of data, such as getting a data object data from https://xxx.yyy.com/api/zzz/, getting the sequence number of the data I want through data.id, and then sending a request to get the desired data.
The way to use callback functions is similar to the above, which is too cumbersome, error-prone, and difficult to change once the logic is complex.
Next, let's sort out several network request methods of js to get rid of callback hell. I hope it will be helpful to the partners who encounter similar problems.
XMLHttpRequest
The first is XMLHttpRequest, which is the famous Ajax in the beginner's front end. The pattern for creating a network request through the XMLHttpRequest object is as follows:
/ / suppose visiting http://localhost:3000/user returns json object {"name": "YouDao"} const xhr = new XMLHttpRequest (); const url = 'http://localhost:3000/user'xhr.onreadystatechange = function () {if (this.readyState = = 4 & & this.status = = 200) {const json=JSON.parse (xhr.responseText) const name=json.name console.log (name)} xhr.open (' GET',url) xhr.send ()
This code first creates a XMLHttpRequest object xhr, then adds a callback function for the readystatechange event to xhr.onreadystatechange, then xhr.open ('GET',url) initializes the request, and finally xhr.send () sends the request.
After the request is sent, the program continues to execute without blocking, which is also the advantage of asynchronous calls. When the browser receives a response, it goes into the callback function of xhr.onreadystatechange. During the whole request process, xhr.onreadystatechange will be triggered four times, and each time the readyState will increase itself, from 1 to 4. The final response data can only be obtained when readyState is 4 in the final stage.
After reaching the fourth stage, it is necessary to judge whether the status code of the response is normal according to the status. Usually, a response code of 200 indicates that the request has not encountered a problem. This code will eventually type YouDao on the console.
As you can see, if you process a request through XMLHttpRequest, you first create a XMLHttpRequest object for each request, and then bind the callback function of the readystatechange event to each object. If multiple requests are strung together, it is troublesome to think about it.
Promise
Promise was introduced in ECMAScript 2015, and if one event depends on the result returned by another event, using callbacks can complicate the code.
The Promise object provides a mode for checking for failure or success of an operation. If successful, another Promise is returned. This makes the writing of callbacks more standardized.
The routines handled by Promise are 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 strands the whole process together, first creating a Promise object, whose constructor receives a function, the first argument of the function is the function resolve when there is no error, and the second argument is the function r eject to be executed after the error.
Resolve refers to the callback function in then after successful execution, and reject refers to the callback function executed in catch after failed execution. The final finally is executed regardless of success or failure and can be used to do some finishing work.
Promise-based web requests can be implemented using the axios library or the fetch that comes with the browser.
The routine for creating a request for axios library 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 fetch,fetch as a browser instead of XMLHttpRequest, API, which does not need to import libraries. Fetch creates requests in a similar way to axios, which is not repeated after it has been shown at the beginning.
Although Promise simplifies the way callback functions are written, it still doesn't get rid of callback hell. If multiple requests are strung together, as I wrote at the beginning, a new Promise will be created in then and eventually become Promise hell.
Async/await
Async/await was introduced in ECMAScript 2017 to simplify the writing of Promise so that asynchronous function calls in code can be executed sequentially and easy to understand.
Let's use the example at the beginning to illustrate:
Get the data directly with fetch:
Const requestOptions = {method: 'GET', redirect:' follow'} Fetch ('https://xxx.yyy.com/api/zzz/', requestOptions). Then (response = > response.json ()). Then (data = > {fetch (' https://xxx.yyy.com/api/aaa/'+data.id,) RequestOptions) .then (response = > response.json ()) .then (data = > {console.log (data)}) .catch (error = > console.error ('error', error)) ) .catch (error = > console.error ('error', error))
After rewriting with async/await:
Async function demo () {const requestOptions = {method: 'GET', redirect:' follow'}; const response = await fetch ('https://xxx.yyy.com/api/zzz/', requestOptions) Const data = await response.json () const response1 = await fetch ('https://xxx.yyy.com/api/aaa/'+data.id, requestOptions) const data1 = await response1.json () console.log (data1)} demo (). Catch (error = > console.error (' error',error))
The rewritten code is clear that there is not so much then behind, so there is no need to be afraid if there are a series of network requests.
When async is placed before the declaration of a function, the function is an asynchronous function, and calling the function returns a Promise.
Await is used to wait for a Promise object, which can only be used in asynchronous functions, and the await expression pauses the execution of the current asynchronous function, waiting for Promise processing to complete.
In this way, if you want a series of asynchronous function calls to be executed sequentially, just put the called functions into a function decorated with async, and add await before the call to make the functions execute sequentially.
This is the end of this article on "what are the ways in which JS implements network requests?". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.