JavaScript

What Is the Difference Between Sequential and Parallel Execution Using async/await?

In JavaScript, async/await makes asynchronous code easier to read and manage. However, how you use await determines whether asynchronous operations run…

D
DevByteTechnical Author
Published
12 min read1 views
What Is the Difference Between Sequential and Parallel Execution Using async/await?

If you've worked with Node.js, you've probably used async/await to handle asynchronous operations. It makes JavaScript code easier to read and helps you avoid deeply nested callbacks or complicated promise chains.

But there's one thing I've noticed developers sometimes misunderstand when learning async/await: writing asynchronous code doesn't automatically mean that multiple operations will run in parallel.

Consider a situation where you're building a dashboard for an e-commerce application. The dashboard needs to fetch user information, retrieve recent orders, and calculate total sales. These operations might involve separate API calls or database queries.

You could execute them one after another, waiting for each operation to finish before starting the next. Or, if the operations are independent, you could start them together and wait for all the results.

Both approaches work, but the execution time can be very different.

This is where sequential and parallel execution become important.

In this article, we'll understand the difference between sequential and parallel execution using async/await, explore practical Node.js examples, and learn when to use each approach in real projects.

What Is Sequential Execution in JavaScript?

Sequential execution means running operations one after another.

The next operation starts only after the previous operation has completed.

When you use await inside an asynchronous function, JavaScript pauses that function's progress until the awaited promise settles. Other JavaScript work can continue while the function is suspended, but the next statement in that function won't execute until the awaited operation finishes.

Let's start with a simple example.

function delay(ms) {
    return new Promise((resolve) => setTimeout(resolve, ms));
}

async function runTasks() {
    console.time("Total Time");

    await delay(2000);
    console.log("Task 1 completed");

    await delay(2000);
    console.log("Task 2 completed");

    await delay(2000);
    console.log("Task 3 completed");

    console.timeEnd("Total Time");
}

runTasks();

Output

Task 1 completed
Task 2 completed
Task 3 completed
Total Time: approximately 6 seconds

Each task waits for the previous one to finish.

The first delay takes around two seconds. After that, the second delay starts and takes another two seconds. Finally, the third delay runs.

The total time is approximately six seconds.

This is sequential execution.

Notice that the example uses setTimeout() to simulate an asynchronous operation. In a real application, these delays could represent database queries, API requests, or file operations.

When Is Sequential Execution Useful?

Sequential execution is useful when one operation depends on the result of another.

For example, imagine you're building a user registration API.

Your application might need to:

  1. Validate the user's information.

  2. Create the user record in the database.

  3. Generate a verification token for the new user.

  4. Send a verification email.

Some of these operations have dependencies.

You cannot reliably generate a token associated with a newly created database record until that record exists. Similarly, you may need the token before sending the verification email.

Here's a simplified example:

async function registerUser(userData) {
    const user = await createUser(userData);

    const token = await generateVerificationToken(user.id);

    await sendVerificationEmail(user.email, token);

    return user;
}

In this example, each step waits for the previous step to finish.

That makes sense because the later operations depend on information produced by the earlier ones.

However, sequential execution isn't always necessary. Sometimes, developers accidentally make independent operations wait for each other, which can increase the overall response time.

What Is Parallel Execution Using async/await?

Parallel execution means starting multiple independent operations without waiting for each one to finish before starting the next.

In JavaScript, a common way to achieve this with promises is to start the operations first and then use Promise.all() to wait for their results.

Let's use the same example, but change how the tasks are executed.

function delay(ms) {
    return new Promise((resolve) => setTimeout(resolve, ms));
}

async function runTasks() {
    console.time("Total Time");

    const task1 = delay(2000);
    const task2 = delay(2000);
    const task3 = delay(2000);

    await Promise.all([task1, task2, task3]);

    console.log("All tasks completed");

    console.timeEnd("Total Time");
}

runTasks();

Output

All tasks completed
Total Time: approximately 2 seconds

Why does this example take around two seconds instead of six?

Because all three timers are started before the code waits for their completion.

The promises represent operations that are already in progress. Promise.all() waits for all three promises to fulfill.

Since the timers run concurrently, the overall time is approximately the duration of one timer rather than the sum of all three durations.

This is a form of concurrent execution, which developers commonly describe as running asynchronous operations in parallel.

There's an important technical distinction here: Promise.all() does not itself start promises or make arbitrary operations execute simultaneously. The operations begin when their underlying APIs are invoked. Promise.all() coordinates waiting for their results.

For typical asynchronous I/O tasks, this approach can significantly reduce the time your application spends waiting.

Understanding the Difference With a Real-World Example

Let's imagine you're developing a dashboard using Node.js, Express, and MongoDB.

When a user opens the dashboard, your backend needs to retrieve three things:

  • User profile information.

  • Recent orders.

  • Product statistics.

Suppose each database operation takes approximately 500 milliseconds.

For simplicity, assume the operations are independent and can run concurrently.

Approach 1: Sequential Execution

You could write your code like this:

async function getDashboardData(userId) {
    const user = await getUser(userId);

    const orders = await getOrders(userId);

    const stats = await getProductStats();

    return {
        user,
        orders,
        stats
    };
}

Here, the application waits for getUser() to finish before calling getOrders().

It then waits for getOrders() before calling getProductStats().

If each operation takes approximately 500 milliseconds, the total waiting time is around 1.5 seconds.

Approach 2: Parallel Execution

If the three operations don't depend on one another, you can execute them like this:

async function getDashboardData(userId) {
    const [user, orders, stats] = await Promise.all([
        getUser(userId),
        getOrders(userId),
        getProductStats()
    ]);

    return {
        user,
        orders,
        stats
    };
}

All three functions are called before Promise.all() waits for their results.

If each operation takes approximately 500 milliseconds and the underlying operations can proceed concurrently, the total waiting time may be closer to 500 milliseconds, plus overhead.

The actual duration depends on database performance, connection-pool limits, query complexity, and other factors.

This is one of the most useful applications of parallel execution in backend development: reducing unnecessary waiting when independent operations are involved.

Sequential vs. Parallel Execution: A Comparison

Let's compare the two approaches directly.

Feature

Sequential Execution

Parallel Execution

Execution pattern

One operation after another

Independent operations are started without waiting for one another

Common approach

Multiple await statements

Promise.all() with independent promises

Total waiting time

Often the sum of operation durations

Often close to the slowest operation's duration

Dependencies

Suitable for dependent operations

Suitable for independent operations

Error handling

Each operation can be handled separately

Promise.all() rejects when one input promise rejects

Resource usage

Usually spreads work over time

Can increase simultaneous resource usage

Common use case

Creating a record before using its ID

Fetching independent dashboard data

One thing to remember is that parallel execution isn't automatically better in every situation.

If an operation depends on another operation's result, running them together may produce incorrect results.

Similarly, starting too many database queries at once can overload your database or exhaust your connection pool.

The goal is to choose an execution pattern that matches the requirements of your application.

What Is the Difference Between Promise.all() and Multiple await Statements?

This is a common question in Node.js interviews.

Consider these two examples.

Multiple await Statements

const user = await getUser();
const orders = await getOrders();

The second function isn't called until getUser() has fulfilled and the first await has resumed execution.

If both operations take 500 milliseconds, the total time may be approximately one second.

Promise.all()

const [user, orders] = await Promise.all([
    getUser(),
    getOrders()
]);

Both functions are called before execution reaches the await on Promise.all().

If both operations can proceed concurrently and take 500 milliseconds each, the total time may be approximately 500 milliseconds.

The main difference is when the operations are started, not simply whether you use the await keyword.

You can also use Promise.all() without writing async/await, but combining the two often makes the code easier to read.

Can You Use Promise.all() With API Requests?

Yes. This is one of the most common examples of concurrent asynchronous execution.

Suppose your Node.js application needs to fetch information from three independent APIs.

You can use the built-in fetch() API available in modern Node.js versions.

async function fetchDashboardData() {
    try {
        const [usersResponse, productsResponse, ordersResponse] =
            await Promise.all([
                fetch("https://api.example.com/users"),
                fetch("https://api.example.com/products"),
                fetch("https://api.example.com/orders")
            ]);

        if (
            !usersResponse.ok ||
            !productsResponse.ok ||
            !ordersResponse.ok
        ) {
            throw new Error("One or more API requests failed.");
        }

        const [users, products, orders] = await Promise.all([
            usersResponse.json(),
            productsResponse.json(),
            ordersResponse.json()
        ]);

        return {
            users,
            products,
            orders
        };
    } catch (error) {
        console.error("Unable to load dashboard data:", error);
        throw error;
    }
}

The first Promise.all() waits for all three HTTP requests to complete.

After the responses arrive, the second Promise.all() parses their JSON bodies concurrently.

Notice that fetch() doesn't automatically reject its promise for HTTP error statuses such as 404 or 500. That's why the code checks each response's ok property.

The example also uses placeholder API URLs. Replace them with actual endpoints when implementing this in a real project.

This pattern can be useful when building dashboards, analytics pages, admin panels, and other interfaces that need data from multiple sources.

What Happens If One Promise Fails?

One important detail about Promise.all() is that it rejects as soon as one of its input promises rejects.

Consider this example:

async function runTasks() {
    try {
        const results = await Promise.all([
            Promise.resolve("Task 1 completed"),
            Promise.reject(new Error("Task 2 failed")),
            Promise.resolve("Task 3 completed")
        ]);

        console.log(results);
    } catch (error) {
        console.error(error.message);
    }
}

runTasks();

Output:

Task 2 failed

The catch block handles the rejection.

However, there's something important to understand: Promise.all() does not automatically cancel the other operations when one promise rejects.

The remaining operations may continue running even though the combined promise has already rejected.

For example, if three database queries are running and one fails, the other two may still finish.

If you need every operation's outcome, including failures, consider Promise.allSettled().

async function runTasks() {
    const results = await Promise.allSettled([
        Promise.resolve("User fetched"),
        Promise.reject(new Error("Orders API failed")),
        Promise.resolve("Statistics fetched")
    ]);

    console.log(results);
}

runTasks();

The result contains a status for every promise.

Successful promises have a fulfilled status, while failed promises have a rejected status.

This approach is useful when a dashboard should display whatever data is available instead of failing completely because one independent service is unavailable.

When Should You Avoid Parallel Execution?

Parallel execution can improve performance, but there are situations where you should avoid it.

1. When One Operation Depends on Another

Imagine you need to create a user before creating a profile associated with that user's database ID.

const user = await createUser(userData);

const profile = await createProfile(user.id);

This sequence makes sense because the second operation requires the ID returned by the first.

Running both operations independently could cause the profile creation to fail or use incorrect information.

2. When Operations Modify the Same Data

Suppose two operations update the same account balance.

Running them concurrently without proper database-level coordination can lead to race conditions or lost updates.

The correct solution may involve database transactions, atomic updates, locking, or other concurrency controls.

Simply switching between sequential and parallel JavaScript code isn't enough to guarantee data consistency.

3. When You Have Too Many Operations

Imagine your API needs to process 5,000 records.

Starting 5,000 database queries simultaneously with Promise.all() may overload your database, consume excessive resources, or exceed connection-pool limits.

A better approach is often to process work in batches or use a concurrency limit.

For example, you might process 20 operations at a time rather than starting all 5,000 together.

The ideal limit depends on the resources available and the requirements of your application.

4. When the Operations Must Happen in a Specific Order

Some workflows require a strict sequence.

For example, you might need to validate a payment request, confirm the transaction with a payment provider, and then update an order's status.

You shouldn't treat these operations as independent if one step depends on the successful outcome of another.

Always consider the business logic before trying to optimize execution time.

Does async/await Make JavaScript Multithreaded?

No. Using async/await doesn't automatically make JavaScript execute code on multiple threads.

This is an important distinction, especially for Node.js developers.

When you use async/await with network requests, timers, or asynchronous filesystem operations, Node.js can manage the waiting without blocking the JavaScript thread in the same way that synchronous operations would.

This allows other work to proceed while an asynchronous operation is waiting for a result.

However, CPU-intensive JavaScript calculations still run on the JavaScript thread unless you use an appropriate mechanism, such as worker threads, to move that work elsewhere.

For example, running a large mathematical calculation inside an async function doesn't automatically make that calculation execute in parallel.

async function calculate() {
    let total = 0;

    for (let i = 0; i < 1_000_000_000; i++) {
        total += i;
    }

    return total;
}

Although calculate() returns a promise, the loop itself is synchronous and can block the JavaScript thread while it runs.

This is why it's important to distinguish between asynchronous execution, concurrency, and CPU parallelism.

For most API calls and database queries, concurrent asynchronous operations can reduce waiting time. For CPU-heavy tasks, you may need a different approach.

Best Practices for Sequential and Parallel Execution

When working on Node.js applications, keep these practices in mind.

Use sequential execution when dependencies exist.

If one operation needs the result of another, use await in the appropriate order.

Use Promise.all() for independent operations.

If several operations can safely start without waiting for each other, starting them together can reduce the total waiting time.

Handle errors properly.

Use try/catch when awaiting promises and choose the appropriate error-handling strategy for your application.

Avoid unbounded concurrency.

Don't launch thousands of resource-intensive operations simultaneously without considering database limits, API rate limits, and memory usage.

Measure performance instead of guessing.

The actual speed improvement depends on the work being performed. Use timing measurements and production metrics to understand whether a change makes a difference.

Keep your code readable.

The fastest implementation isn't always the best one if it introduces unnecessary complexity or makes failures difficult to handle.

Final Thoughts

Sequential and parallel execution are two important concepts to understand when working with async/await in Node.js.

Sequential execution runs operations one after another and is useful when each step depends on the result of the previous one.

Parallel execution starts independent asynchronous operations without waiting for each one individually. Using Promise.all() is a common way to wait for all their results together.

For example, creating a database record before using its ID is a good reason to use sequential execution. Fetching independent user, order, and product data for a dashboard is a good candidate for concurrent execution.

The main lesson is simple: don't use await one operation at a time when those operations are independent and can safely run together.

At the same time, don't force everything to run concurrently just because it looks faster. Consider dependencies, error handling, resource limits, and data consistency before choosing an approach.

Once you understand when to use sequential execution and when to use Promise.all(), you'll be able to write more efficient and reliable asynchronous code in your Node.js applications.

For more details, check the official MDN documentation for async functions and Node.js documentation for promises.

D
DevByteAuthor

Technical author and software engineer at DevByte. Writing deep-dive tutorials on distributed systems, modern full-stack web architectures, and cloud deployments.

Keep Exploring

Related Engineering Dispatches

More guides and architectural patterns you might find valuable.

Browse All Articles↘
What Are Promises in JavaScript?
•17m

What Are Promises in JavaScript?

In JavaScript, a Promise is an object that represents the eventual success or failure of an asynchronous operation. Promises help you manage operations such as…

30