Better Programming

Advice for programmers.

Follow publication

Member-only story

How To Return a Response From Asynchronous Calls in JavaScript

Johannes Baum
Better Programming
Published in
3 min readJan 25, 2021

Stormtrooper by a bridge
Photo by Angelo Abear on Unsplash.

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 rejected
  • fulfilled: The operation was completed successfully.
  • rejected: The operation failed.

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Johannes Baum
Johannes Baum

Written by Johannes Baum

Creator of GridEngine (https://github.com/Annoraaq/grid-engine) 👾 Software Engineer 🚀 JavaScript/TypeScript

No responses yet