Asynchronous Programming in JavaScript: Callbacks, Promises, and Async/Await

And then there is the most dangerous risk of all, the risk of spending your life not doing what you want on the bet you can buy yourself the freedom to do it later.

Haruto Tanaka
4 Min Read

Welcome back to our series of tutorials on JavaScript. In our previous chapter, we got acquainted with how to work with errors and exceptions. Today we start a new chapter and a very important topic: asynchronous programming. The techniques of asynchronous programming are bread and butter when doing today’s web and application development. They allow performing resource-intensive or time-consuming operations, as loading data or processing files without blocking the main thread.
Basics of Asynchronous Programming
Overall, any such operation in JavaScript, like API request or filing reading or some time-consuming computation, is performed asynchronously. There are mainly three ways of dealing with such operations: callbacks, Promises, or Async/Await.

Callback Functions

They are functions called after a certain operation is completed. It is one of the oldest ways to deal with such operations-asynchronous callbacks.

function fetchData(callback) {
    setTimeout(() => {  // Simulating data loading
        callback('Data loading complete');
    }, 1000);
}

fetchData((data) => {
    console.log(data);  // Output: Data loading complete
});

Promise

A Promise is a more advanced way to handle asynchronous programming. A Promise represents an operation that will eventually complete (or fail) and return a value.

function fetchData() {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve('Data loading complete');
        }, 1000);
    });
}

fetchData().then(data => {
    console.log(data);  // Output: Data loading complete
}).catch(error => {
    console.error(error);
});

Async/Await

Async/Await is a syntax based on Promises that makes asynchronous code look similar to synchronous code, making it more intuitive and easier to understand.

async function fetchData() {
    const response = await new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve('Data loading complete');
        }, 1000);
    });
    console.log(response);  // Output: Data loading complete
}

fetchData();

Example: Asynchronous Data Loading

Let’s demonstrate how to use asynchronous techniques to load data from the web using the fetch API. Fetch is a common method for network requests that returns a Promise.

async function loadPosts() {
    try {
        let response = await fetch('https://jsonplaceholder.typicode.com/posts');
        let data = await response.json();
        console.log(data);  // Output: Loaded post data
    } catch (error) {
        console.error('Data loading failed:', error);
    }
}

loadPosts();

Summary

At the end of this tutorial, you must have had at least a glimpse of how to use JavaScript to implement Asynchronous programming. It has shown how to use and implement callbacks, Promise and Async/Await in handling the asynchronous operation in JavaScript. All these tools and technique, help you to manage effectively your asynchronous task, which improve the performance and user experience for your application. Keep on practicing the technique and implement it in real-world problem. In the next lesson, we will see more.

Share This Article
Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *

one × five =