ASYNC/AWAIT
JavaScript Asynchronous function
INTRODUCTION
JavaScript has a program language that follows a synchronous operation, whereby a task is performed before another task is executed. Step by step task execution. But such operations can become a bit of a problem when there’s a need to get data from a server or an endpoint, which will take some time to perform, with a synchronous operation. Hence the asynchronous operation.
______________ & & ______________
"Asynchronous JavaScript is a function running in parallel with other functions" (w3schools.com/js). Asynchronous operations are performed when data needs to be gotten from a server or an endpoint without disrupting or blocking other codes. It allows JavaScripts operations to run smoothly, while data is generated from an endpoint. Asynchronous is a blocking code.
There some functions that are done under asynchronous JavaScript, namely:
JavaScript promises
JavaScript callbacks
Async and await
Async and await is the main focus of this piece.
Async makes a function return promises, while await makes a function wait for a promise. This word keywords are used when we are fetching data with the JavaScript keyword "fetch".
Before I delve into the details, it is important to know about JavaScript Promises and its parameters (.then and .catch methods). Read more on javascript.info or w3schools.com/JS.
"async" is used at the beginning of a function, to initiate the asynchronous operations in JavaScript and "await" is used to wait for the endpoint to generate the data. The function returns promise and the data gotten back are in a format called JSON. Which are in objects format inside an array. It comprises data of different features.
From the above example, we see that async returns a promise even without a url inputted.
Now let's insert a url and see our result using the ".then" to pass the data, and ".catch" to catch errors that might occur during the process.
From the above images, we can see the results of the endpoints, the data in each object. Which can later be used on our web. If there’s any error, the catch will capture the error.
But there’s another way of catching errors under async/await, using the "throw" function.
As such, we can see where the errors lie and it can easily be rectified.
Async/await helps us to write reusable, non-blocking, easy and simple codes to generate data without disrupting the flow of our JavaScript codes. Async/await allows us to chain multiple promises together as we want.
REFERENCES
W3 Schools
JavaScript-MDN
JavaScript info
Net Ninja
Thank you for reading!!!
🖊️ MOHTech