By design, JS has both synchronous and asynchronous functions. Most activities are synchronous, but the few that are usually take some time to be completed. It was common to use "callbacks functions" to resolve the gap between the execution of the function and its response. Without callbacks, it was very easy to create uninitialized variables if a line of code was executed before a response has been return. Personally, I had a custom function which used AJAX in jQuery to GET or POST data. I passed JSON data and a callback function as properties. The data would be sent to the API and the callback function would be upon success.
The current Fetch API is asynchronous and ECMA6 allows for a function to be defined as being async
and thus you can force your script to
wait
for
a result rather than providing the user with a promise. A promise being the eventual completion (or failure) of an asynchronous operation and its resulting value. This replaces the need for callbacks, as this makes your function synchronous.
In React, the useEffect
hook allows uses to re-render a component when state has changed. Monitoring state can be the tricky part of using the useEffect
function. Written correctly, your component will re-render, only when necessary. Written incorrectly, and you can create an infinite loop as on each reload the dependency is renewed, causing useEffect
to re-render the component. It's necessary to remember that useEffect
is scheduled after a render cycle. This makes it perfect for asynchronous functions. When executed, the useEffect
triggers a re-render that applies the new state to the component, i.e. the data from your asynchronous function. useEffect
is a power tool, but use it wisely.