Skip to content
-
Subscribe to our newsletter & never miss our best posts. Subscribe Now!
  • https://www.facebook.com/
  • https://twitter.com/
  • https://t.me/
  • https://www.instagram.com/
  • https://youtube.com/
Code and Soft Code and Soft

Code and Soft

Code and Soft Code and Soft

Code and Soft

  • Home
  • Gadgets
  • Software
  • Mobile & App
  • Home
  • Gadgets
  • Software
  • Mobile & App
Subscribe
Close

Search

Software

Understanding Promises and Async Code in JavaScript

By hosanarenee@gmail.com
September 22, 2026 8 Min Read
Comments Off on Understanding Promises and Async Code in JavaScript

JavaScript is used to create websites and web applications that can respond quickly to what users do. A page may need to load information from a server, save a form, display an image, or check some information before showing the result. These tasks often take a little time. If JavaScript had to wait for every task to finish before doing anything else, websites would feel slow and unresponsive.

This is where promises and asynchronous code become important. They help JavaScript handle tasks that take time without making the whole application wait. Although these ideas may sound difficult at first, they become much easier when you understand what is happening in simple terms.

In this article, we will look at what asynchronous code means, what a promise is, how promises work, how async and await make promises easier to use, and where these features are useful in everyday JavaScript development.

What Does Asynchronous Code Mean?

Before understanding promises, it is helpful to understand the idea behind asynchronous code.

Imagine that you are making a cup of tea. You put water on the stove and wait for it to boil. While the water is heating, you do not have to stand still and stare at the pot. You can prepare the cup, get some biscuits, or do something else. When the water is ready, you can continue with the next step.

Asynchronous JavaScript works in a similar way.

When JavaScript starts a task that may take some time, it can allow other work to continue instead of stopping everything until that task is finished. When the task is ready, JavaScript can deal with the result.

A simple example is waiting for a few seconds before running some code.

setTimeout(() => {

    console.log(“The task is finished”);

}, 2000);

console.log(“This runs first”);

Here, JavaScript starts the timer and then immediately prints “This runs first”. After two seconds, it prints “The task is finished”.

This is asynchronous behavior. JavaScript does not stop all other work while the timer is running.

Why Do We Need Asynchronous JavaScript?

Many common tasks in web applications take time to complete. Getting information from a server is one of the most common examples.

Suppose a weather website needs to get today’s weather information from a server. The request may take a short amount of time because the browser needs to send a request, wait for the server, and receive the answer.

If JavaScript stopped completely during this process, the user might not be able to click buttons, type in a search box, or interact with the page.

Asynchronous code allows the browser to keep working while it waits for the answer.

The same idea applies when loading files, sending information to a server, reading data, or waiting for a user action. Instead of making the entire page wait, JavaScript can start the task and handle the result when it becomes available.

What Is a Promise in JavaScript?

A promise is an object that represents the future result of a task.

The easiest way to think about a promise is to imagine ordering something online. After placing an order, you do not have the product immediately. Instead, you receive confirmation that your order is being processed. Later, the product may arrive, or something may go wrong with the delivery.

A JavaScript promise works in a similar way. It represents a result that is not available yet.

A promise can be in one of three basic conditions. It can still be waiting, it can finish successfully, or it can finish with an error.

For example:

const order = new Promise((resolve, reject) => {

    setTimeout(() => {

        resolve(“Your order is ready”);

    }, 2000);

});

In this example, the promise waits for two seconds. After that, it completes successfully and sends the message “Your order is ready”.

The word resolve is used when the task finishes successfully. The word reject is used when something goes wrong.

Here is a simple example that can fail:

const order = new Promise((resolve, reject) => {

    const success = true;

    if (success) {

        resolve(“Order completed”);

    } else {

        reject(“Order failed”);

    }

});

The promise now has two possible results. It can complete successfully or report a problem.

Using Then With a Promise

Once a promise has finished, we usually want to do something with the result. The .then() method lets us do that.

order.then((message) => {

    console.log(message);

});

If the promise completes successfully, the message is received inside .then().

For example:

const message = new Promise((resolve) => {

    setTimeout(() => {

        resolve(“Hello from the promise”);

    }, 2000);

});

message.then((result) => {

    console.log(result);

});

The browser waits for the promise to complete. Once it finishes, the result is passed to the function inside .then().

This is useful when working with information that arrives later.

Handling Errors With Catch

Not every task finishes successfully. A server request may fail, an internet connection may stop working, or some information may not be available.

Promises provide .catch() for handling these problems.

const task = new Promise((resolve, reject) => {

    reject(“Something went wrong”);

});

task

    .then((result) => {

        console.log(result);

    })

    .catch((error) => {

        console.log(error);

    });

In this example, the promise rejects the task. Because of that, the code inside .catch() runs.

Using .catch() is important because users should receive a useful response when something goes wrong instead of seeing a broken page.

What Is Finally?

Promises also have a .finally() method. It runs after the promise finishes, whether the result was successful or unsuccessful.

For example:

task

    .then((result) => {

        console.log(result);

    })

    .catch((error) => {

        console.log(error);

    })

    .finally(() => {

        console.log(“Task finished”);

    });

The code inside .finally() will run after either .then() or .catch().

This can be useful when you want to hide a loading message after a task is complete. It does not matter whether the task succeeded or failed; the loading message still needs to disappear.

What Is Async in JavaScript?

Promises work well, but long chains of .then() can sometimes become difficult to read. JavaScript provides async and await to make promise-based code easier to understand.

The async keyword is placed before a function.

async function getMessage() {

    return “Hello”;

}

An async function always returns a promise.

Even though the function appears to return a simple piece of text, JavaScript treats the result as a promise.

getMessage().then((message) => {

    console.log(message);

});

The async keyword is especially useful when combined with await.

Understanding Await

The await keyword tells JavaScript to wait for a promise to finish before moving to the next line inside that function.

For example:

function getMessage() {

    return new Promise((resolve) => {

        setTimeout(() => {

            resolve(“Message received”);

        }, 2000);

    });

}

async function showMessage() {

    const result = await getMessage();

    console.log(result);

}

showMessage();

Here, getMessage() returns a promise. The await keyword waits for that promise to finish. Once it completes, the result is stored in result.

This code is often easier to read than a long .then() chain.

It almost looks like JavaScript is performing the steps one after another. However, await does not freeze the entire website. It only waits within that asynchronous function while other work can continue.

Async and Await Together

The real strength of async and await becomes clear when several tasks need to happen one after another.

Imagine that an application first needs to get a user account and then use that account information to get the user’s orders.

Using promises, the code might look like this:

getUser()

    .then((user) => {

        return getOrders(user.id);

    })

    .then((orders) => {

        console.log(orders);

    })

    .catch((error) => {

        console.log(error);

    });

The same idea using async and await can be written like this:

async function showOrders() {

    try {

        const user = await getUser();

        const orders = await getOrders(user.id);

        console.log(orders);

    } catch (error) {

        console.log(error);

    }

}

For many developers, the second version is easier to read because the steps are clearly shown from top to bottom.

Handling Errors With Try and Catch

When using async and await, errors from promises can be handled with try and catch.

async function loadData() {

    try {

        const result = await getData();

        console.log(result);

    } catch (error) {

        console.log(“Could not load the data”);

    }

}

The code inside try contains the task that may fail. If the promise fails, JavaScript moves to the catch section.

This makes it easier to show users a useful message when something goes wrong.

For example, a website could display “Unable to load your account. Please try again.” instead of leaving the user wondering why nothing appeared.

Working With Real Server Requests

One of the most common uses of promises is getting information from a server.

Modern JavaScript commonly uses fetch() for this.

async function getUsers() {

    try {

        const response = await fetch(“https://example.com/users”);

        const users = await response.json();

        console.log(users);

    } catch (error) {

        console.log(“Could not get users”);

    }

}

The fetch() function sends a request and returns a promise. The await keyword waits for the response. Then response.json() reads the information from the response.

This pattern is widely used in websites and web applications.

The exact address used in a real project would normally point to the application’s own server or another service that provides the required information.

Running Several Tasks at the Same Time

Sometimes tasks do not depend on each other. In that situation, there is no need to wait for one task before starting another.

JavaScript provides Promise.all() for this kind of situation.

Imagine that a page needs to load user information and product information. If the two requests are independent, they can be started together.

async function loadPage() {

    try {

        const [user, products] = await Promise.all([

            getUser(),

            getProducts()

        ]);

        console.log(user);

        console.log(products);

    } catch (error) {

        console.log(“Something went wrong”);

    }

}

Here, both tasks can run at the same time. The code waits until both promises finish.

This can make an application faster when several independent pieces of information are needed.

Common Mistakes With Async Code

One common mistake is forgetting to use await when a result is needed.

For example:

async function showUser() {

    const user = getUser();

    console.log(user);

}

If getUser() returns a promise, user will contain the promise rather than the final user information.

It should normally be written as:

async function showUser() {

    const user = await getUser();

    console.log(user);

}

Another mistake is forgetting to handle errors. Network requests can fail, so important asynchronous tasks should have a way to deal with problems.

It is also important to remember that await can only be used directly inside an async function in normal JavaScript code.

Promises Make JavaScript Easier to Manage

At first, promises, async, and await can seem like extra things to learn. In reality, they help make JavaScript code easier to manage.

A promise tells us that a result will be available later. .then() lets us work with a successful result, while .catch() helps us handle a problem. async allows a function to work with promises in a cleaner way, and await lets us wait for a promise inside that function without blocking the whole page.

Once these ideas become familiar, many common JavaScript tasks become much easier to understand.

Final Thoughts

Promises and asynchronous code are an important part of modern JavaScript. Websites constantly need to wait for information, whether that means loading data from a server, reading a file, saving information, or completing another task that takes time.

The main idea is simple: JavaScript can start a task and continue doing other work while waiting for the result. A promise represents that future result. If the task succeeds, JavaScript can use the result. If it fails, the problem can be handled.

async and await make this process easier to read because asynchronous code can be written in a style that feels more natural. With regular practice, promises and asynchronous code stop feeling complicated and become normal tools for building useful JavaScript applications.

Tags:

Async Code in JavaScriptPromises in JavaScript
Author

hosanarenee@gmail.com

Follow Me
Other Articles
Previous

Australian Travel Apps for Booking Flights and Accommodation

Next

How JavaScript Works With APIs and Web Applications

Discover insightful articles, expert perspectives, useful guides, and inspiring stories covering topics that matter to you.

Quick Links

  • Home
  • Privacy Policy
  • Terms & Conditions
  • Write For Us

Category

  • Home
  • Gadgets
  • Software
  • Mobile & App

Get In Touch

Have a question or want to connect with us? We'd love to hear from you.

demandexcellence123@gmail.com

Contact Us
Copyright 2026 — Code and Soft. All rights reserved.