Javascript 101: Handling Asynchrony — Part 1

Ewere Ebie
Geek Culture
Published in
4 min readNov 22, 2021

--

When programs interact with things outside of the processor like communicating over a computer network, the operating system switches the processor between multiple running programs so it does not sit Idle. This is a classic case of asynchrony. Javascript being single-threaded has a number of ways of dealing with Asynchrony. Let's get to know them 😊.

Callbacks

Callbacks are the fundamental unit of asynchrony in JS. In this approach to asynchronous programming, a function that performs a slow action takes an extra argument, a callback function. The action is started, and when it finishes, the callback function is called with the result.

In the example above, the setTimeout function, available both in Node.js and in browsers, waits a given number of milliseconds (a second is a thousand milliseconds) and then calls a function(Callback).

This style of programming is easy to implement, but the indentation level increases with each asynchronous action and leads to a dilemma referred to as Callback Hell.

Why Callbacks aren’t so great

First, our brains plan things out in sequential, blocking, single-threaded semantic ways, but callbacks express asynchronous flow in a rather nonlinear, which makes reasoning properly about such code much harder.

Second, and more importantly, callbacks suffer from inversion of control in that they implicitly give control over to another party (often a third-party utility not in your control!) to invoke the continuation of your program. This control transfer leads us to a troubling list of trust issues, such as whether the callback is called more times than we expect.

Promises — A better approach

Instead of arranging for a function to be called at some point in the future, we can return an object that represents this future event.

A promise is an asynchronous action that may complete at some point and produce a value. It is able to notify anyone who is interested when its value is available.

To create a promise, you can use Promise as a constructor. It has a somewhat odd interface — the constructor expects a function as an argument, which expects two functions — resolve(for success path) and reject(for error path) during its invocation.

What we see above is a promise chain that expresses async flow in a sequential fashion. To get the result of a promise, you can use its then method. This registers a callback function to be called when the promise resolves and produces a value. But that’s not all the then method does. It returns another promise, which resolves to the value that the handler function returns. The catch method is used to handle errors.

ES7 Async and Await

A more recent addition to the JavaScript language is async functions and the await keyword, part of the so-called ECMAScript 2017 JavaScript edition. These features basically act as syntactic sugar on top of promises, making asynchronous code easier to write and to read afterward

This is what calling the CallEndpoint from our previous examples would look like if we incorporated async and await. The async keyword, which you put in front of a function declaration turns it into an async function. An async function returns a Promise by default and expects the possibility of the await keyword being used to invoke asynchronous code

The main advantage of promises is that they simplify the use of asynchronous functions. Instead of having to pass around callbacks, promise-based functions look similar to regular ones: they take input as arguments and return their output. The only difference is that the output may not be available yet.

Conclusion

It’s been fun right? we’ve seen the most common implementation of asynchrony in JS via callbacks and have examined its drawbacks. Promises however offer a better programming interface and the closest resemblance to normal functions in javascript using async/await. Promises don't get rid of callbacks, they just redirect the orchestration of those callbacks to a trustable intermediary mechanism that sits between us and another utility. Promises are awesome. Use them!

Next stop — Handling Asynchrony — Part 2

References

--

--

Ewere Ebie
Geek Culture

I write because it’s less exhausting than speaking. And its fun