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.
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.
Top comments (0)