Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
December 11, 2022 12:30 am GMT

Making Asynchronous Requests with Promise and Await Functions

The promise method was introduced before the await method to make an asynchronous request for fetching data. It handles asynchronous requests with an initial state that needs time to process to return a value. When the request is done pending, it will either return a fulfilled value or an error causing an incomplete operation.

In this example, the declared terms state variable is passed to the useEffect hook which then becomes the effect that makes the asynchronous request. The callback function is called on once by including an empty dependency array. If the array was not included the function would constantly render. The fetchPromise variable is given a function using an axios request library. This will make an asynchronous request to the JSON. The .then method is used to obtain the data that responds in objects with key.values . A catch block can be used to identify any errors along the way.

Image description

When promises begin to accumulate it becomes difficult to follow. The async function is more organized and basically the same code as the promise method. The await keyword is used to wait for the promise to be processed first before proceeding. JavaScript requires that the await method can only be used within an async() function. To catch errors, wrap the entire function with a try-catch block. Utilizing the async/await, it's an easier and cleaner way for syntax to flow.

Image description


Original Link: https://dev.to/juliannehuynh/making-asynchronous-requests-with-promise-and-await-functions-3cb9

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To