Member-only story
How To Return a Response From Asynchronous Calls in JavaScript
Leverage promises in your asynchronous functions
People who are new to asynchronous programming are often confused by the following situation:
While this example shows a specific use case for an AJAX call, it represents a much more general pattern: synchronously returning the result of an asynchronous function. Though transforming an asynchronous call into a synchronous one is not possible in JavaScript, I will show you how to solve your problem without destroying the idea behind asynchronous programming.
Types of Asynchronous Functions
Before we jump to a conclusion, we should take a quick look at the most common types of asynchronous functions. They differ in the way they provide their asynchronously gathered value (or simply how they finish whatever they are supposed to do). There are three prominent ways of doing this:
1. Callbacks
A function might take a callback function as a parameter and will call this function with the demanded value whenever it is finished. An example of this is the previously shown ajaxCall
function that takes a callback function as its first parameter. This callback function is called whenever ajaxCall
is finished with its HTTP request. Further, that callback function takes the result of the request as its first parameter. That is how you get the value.
2. Promises
Promises came with ECMAScript 6 (ES2015). A promise is an object that is immediately (synchronously) returned from an asynchronous function and enables you to track the state of that function. A promise can be in one of the following states:
pending
: (initial) neither fulfilled nor rejectedfulfilled
: The operation was completed successfully.rejected
: The operation failed.