Asynchronous Programming in JavaScript

Asynchronous Programming in JavaScript

When a program is executed by the processor it runs straight, with only one thing happening at a time. There are many programs that interact with the things outside other than the processor like a network request, data read from the hard disk. In this era in which computers have multiple processor cores available there’s no sense sitting there waiting for something when you could let the other task come along on another processor core and let you know when it’s done.

When a program is executed by the processor it runs straight, with only one thing happening at a time. There are many programs that interact with the things outside other than the processor like a network request, data read from the hard disk. In this era in which computers have multiple processor cores available there’s no sense sitting there waiting for something when you could let the other task come along on another processor core and let you know when it’s done.

This lets us get other work done in the meantime, which is the basis of asynchronous programming. It is up to the programming environment we are using (web browsers/node in our case) to provide us with APIs that allow us to run such tasks asynchronously.

There are two main types of asynchronous code style one can come across in JavaScript code, old-style callbacks, and newer promise-style code. Let us review each of these in turn.

Callbacks:

A callback is a function that is to be executed after another function has finished executing — hence the name ‘call back’.

It is a function passed into another function as an argument to be executed later.

The function that takes a callback function as an argument is known as a High-Order function.

Callbacks are a way to make sure a certain code doesn’t execute until the other code has already finished execution.

Ideally, the function that performs an async action takes an extra argument, a callback function. When the action finishes, the callback function is called with the result.

Let us see an example:

fs.readFile('/input.json', function (error, data) {
  if(error) {
    //handle error logic
    console.log(error);
    return;
  }
//no error process data
  console.log(data);
})

In the above code snippet, we are using the readFile method in fs class (available as node API). This method reads a file asynchronously. It takes a callback function as an argument (here second argument) which is being called when the reading of the file is completed or there is an error in the process.

The problem with the callback arises only when we have a callback having another callback function as an argument creating a nested callback structure known as “Callback Hell”. As the number of nesting increases, it becomes difficult to manage and understand. It looks something like this.

firstFunction(args, function() {
  secondFunction(args, function() {
    thirdFunction(args, function() {
      // And so on…
    });
  });
});

Promises:

Promises are a first-class representation of a value that may be made available in the future.

It allows us to associate handlers with an asynchronous action’s eventual success value or failure reason.

This lets asynchronous methods return values like synchronous methods: instead of immediately returning the final value, the asynchronous method returns a promise to supply the value at some point in the future.

promises asynchronous javascript programming

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

JavaScript Asynchronous Operation — Read File Directory with Callback or Promises

JavaScript is a synchronous, blocking, single threaded language. Synchronous single threaded means JavaScript waits for the task to be completed before being able to move on to the next task.

A Beginner’s Guide To Promises In JavaScript

Hopefully you will understand it this time :) A Beginner’s Guide To Promises In JavaScript

Understanding Asynchronous Javascript: Promises

Understanding Asynchronous Javascript: Promises - Hey there! It’s Christopher. I have been avoiding this topic for a while because of fear. Haha I enjoy admitting my weaknesses so it can…

JavaScript Promise: Methods Comparison

What are promises and what is the difference between Promise.all, Promise.allSettled, Promise.race and Promise.any?

Promises in JavaScript: Asynchronous Programming & Requests - Jelly Drop

Learn how to use Promises in JavaScript. We'll walk through: * Reviewing what are promises? How you can use resolve and reject in promises * Making requests in a promise with the fetch API * Using Promise.all to wait for multiple requests. What JavaScript fundamentals do you want to learn in the next Jelly Drop? Leave your suggestion in the comments!