Welcome to the third installment of the React Vernacular Campaign series, where we're going to dive deeper into asynchronous operations in JavaScript and introduce two important keywords: Async and Await. In this post, we'll demonstrate the concepts of asynchronous operations through real-world examples, as well as how you can use Promise, Fetch, Async, and Await to handle asynchronous code more In this article, we will demonstrate the concept of asynchronous operations and how to use Promise, Fetch, Async, and Await to handle asynchronous code more effectively.
Table of contents
TogglePreface
Asynchronous operations are becoming more and more important in modern web development. In this article, we will start from the basic concepts, and discuss the principles of asynchronous operations and how to handle asynchronous situations with advanced JavaScript syntax.
This post is about asynchronous JavaScript
- asynchronous
- Promise & Fetch
- Async & Await
- Building Promise Objects
Asynchronous
Asynchronous is an essential concept in development, and in previous code it was currently a Synchronous concept, meaning that the program would run sequentially.
However, in the process of developing a web page, sometimes it is necessary to perform asynchronous actions, such as: the user clicks on the following form to send, we must wait for the end of the data transfer, and get the server to return the data to know whether it is successful or not.
It would be a mistake to run the success or failure of the screen directly through JavaScript before the server returns the results.
There are also syntaxes in modern JavaScript that deal with asynchronous execution, including Promise and Async & Await, which are described next.
Promise & Fetch
Promise
An asynchronous request usually has two outcomes, success and failure, but in practice there are three states, Fulfilled, Rejected, and Pending. The Promise object makes it clear what the current state of an unsynchronized request is when it is executed.
Fetch
Before the fetch function was available, getting API data was quite a hassle and could require more than 20 lines of code. However, ECMA has added the fetch syntax to make it more convenient and it only takes a couple of lines to complete the "fetching of API" data.
Directly with an api example to do examples, this side of the Internet to find a free api
https://api.thecatapi.com/v1/images/search
If the reader enters it directly into the browser, they will see a return object containing the id, url, width, height, and so on.
How to use the code to get the api data?
fetch("https://api.thecatapi.com/v1/images/search") .then(res=>res.json) .then(console.log) .catch(console.error)
Just use the fetch function and pass the URL as an argument, and use the then or catch function to execute the next program in sequence.
In the above code, we first type an api, get the return result through the first then function, and print out the message through the second then function. Lastly, through the catch function, if it fails, a failure message will be printed.
Async & Await
JavaScript Async
Another more common and widely used asynchronous syntax is to use Async & Await asynchronous functions, which are more concise and easier to understand than Promise & Fetch, and are more in line with our reading habits.
If you rewrite the above fetch then to async & await syntax
const getCatData = async() => { let res = await fetch("https://api.thecatapi.com/v1/images/search") let { results } = await res.json() console.log(results) } getCatData() /* [ { id: "ac5", url: "https://cdn2.thecatapi.com/images/ac5.jpg", width: 565, height: 551 } ] */
Use the async keyword in the first line of the function to tell the computer that this is an asynchronous function, and then just add the await keyword in front of any asynchronous request that needs to wait to complete the asynchronous function. So how do we get the failure message? We just add the try & catch syntax to async & await, so that we can run the program inside the try first, and handle the failure status of the Promise in the catch.
const getCatData = async() => { try { let res = await fetch("https://api.thecatapi.com/v1/images/search") let { results } = await res.json() console.log( results) } catch (error) { console.log(error) } } getCatData()
Building Promise Objects
As mentioned above, Promise has three states, Fulfilled, Rejected, and Pending, but in terms of results, they can all be summarized into two outcomes, Success and Failure. So when executing an asynchronous function, you can also send back the result of the execution and use the Promise object to store it.
const getCatData = () => new Promise((resolves, rejects) => { const api = "https://api.thecatapi.com/v1/images/search" const request = new XMLHttpRequest; request.open("GET ", api); request.onload = () => { request.status === 200 ? resolves(JSON.parse(request.response).results) : rejects(Error(request.statusText)) } request.onerror = err => rejects(err); request.send() })
Conclusion
This article explains the concept of asynchronous (Asynchronous) and some implementations. However, asynchronous itself is a relatively difficult concept, and some of the syntax is a bit difficult. Readers are also welcome to bookmark this article and come back to it in the future. Go over and review this content. If you have any suggestions or questions, please leave a message! If you like this series of articles, please feel free to click like and share so that more people can see it~
Other React article references
React Vernacular Campaign 01-JavaScript ES6
React Vernacular Campaign 02-JavaScript ES6 Object
Why do big companies use Nx ? Monorepo Tool 5 Minute Quick Build
Do you really know Monorepo? 5 minutes to learn about front-end mega-architecture.