JavaScript Async & Callbacks
Asynchronous calls and callbacks are how JavaScript is able to respond to user events that occur after the browser has loaded the DOM. This type of programming is commonly referred to as event-driven programming.
In event-driven programming, once an event occurs, its registered callback to that event fires off its functionality. An event could occur from many varying incidents, such as removing an input field from a web form, or retrieving data from a remote web service.
Let’s take a look
Async call with a Callback
// get data from remote url
getJSON(url, function(err, data){
// check for errors
// no errors - process data
// check data condition
// check another condition
// else do this condition
});
The data returned from calling our remote web service, fires the callback function with either the data or an error returned as a dynamic argument.
Using a callback for a simple event is fine. However, if an event contains multiple conditions that need to be checked, then callback functions can become hard to read and maintain. In these more complex cases, JavaScript Promises are the solution.
JavaScript Promises
JavaScript promises are considered a best practice when “calling back”. Promises make callback functionality easier to read by eliminating the need for convoluted error and data conditional checking.
The reason is due to a specific condition will not fire, unless it occurs.
Let’s take a look
Async Using a Promise
// our promise
var promiseData = getRemoteData(url);
promiseData.then(function(data){
// do something interesting
// with the returned data
});
We create a promise variable named promiseData and then call the remote web service like before.
JavaScript promises have a then method defined on them, and this is the location where we create our callback functionality.
If any side effects occur, such as an error, we don’t have to check for this condition, because our then method will only fire the callback if the data is returned. If the data does not return, the then method never executes.
And that’s it! There’s obviously a million other examples between the two, but this gives an simple clear cut practical solution on why you would use promises.
Happy coding! 😀