DEV Community

Cover image for Asynchronous Programming in JavaScript: The Basics
Haastrup Elijah
Haastrup Elijah

Posted on

Asynchronous Programming in JavaScript: The Basics

Making Sense of Asynchronous

Just another English word with its own meaning.

In the most basic sense, asynchronous is used to describe anything that does not depend on time nor keep to time. Not because It is always showing up late, just that it does not have any contract with time so it is not tied to time.

Let's establish a dictionary meaning of asynchronous.

: not simultaneous or concurrent in time : not synchronous
asynchronous sound --> Merriam Webster dictionary

Asynchronous programming

introduction

The focus of asynchronous programing is to achieve non-blocking running of tasks within a program. Some programming languages allow programmers to execute any task using the non-blocking feature within a programming language.

Non-blocking:

This approach allows us to run a task(usually non-time dependent) in the background without waiting for the result before moving on to the next task, unless the programmer decides that the next task(either asynchronous or synchronous) depends on the result from the current task.

Asynchronous Operations in JavaScript

  • Timer operation: using setTimeOut, setTimeInterval and setimmediate(in nodeJs)
  • File read/write
  • HTTP Requests(API calls with built-in functions like XMLHttpRequest and fetch)
  • CPU-intensive operations: sorting or searching large arrays of data
  • CSS animations and transition/transform

Callback Function

If you have been following, you would have thought about it: How do we know that the asynchronous task is done and the result is ready?

JavaScript uses Callback function. Callback functions are regular functions that are passed as an argument to another function.

It is the responsibility of a callback in JavaScript to allow us act on the result of an asynchronous operation immediately they are available.

function showResult(result) {
//show result now
document.body.innerHTML = result
}

function getData(callback) {
  // get data from api call
  const result= { /* ... */ };
  // Call the callback with the fetched data
  callback(result);// calling the callback when result is available
}
getData(showResult)// using showResult function as a callback
Enter fullscreen mode Exit fullscreen mode

Caution on the use of callbacks

Callbacks are good if used carefully, but when it gets too much, it results in what we call "callback hell" i.e. callback inside another callback - nested callbacks

function getUserData(userId, callback) {
  getUserProfile(userId, function(userProfile) { //callback 1
    getUserPosts(userProfile.id, function(userPosts) { //callback 2
      getPostComments(userPosts[0].id, function(postComments) { //callback 3
        callback(postComments); //callback 4
      });
    });
  });
}
Enter fullscreen mode Exit fullscreen mode

as you can see, it will require some level of extra effort to read this code. The code readability suffers with more nested callback.

In the next article, I will explain PROMISES, in basic terms as usual, and explore how they help take away the problem of callback hell by providing an alternative way of organizing our callbacks in a less nested manner.

Let me know if you have any suggestions or questions in the comments.
You can reach me on linkedin and Twitter: killcodeNG.

Image of Datadog

Master Mobile Monitoring for iOS Apps

Monitor your app’s health with real-time insights into crash-free rates, start times, and more. Optimize performance and prevent user churn by addressing critical issues like app hangs, and ANRs. Learn how to keep your iOS app running smoothly across all devices by downloading this eBook.

Get The eBook

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay