w3resource

How to use Promise chains for Sequential Async tasks?


Promise Chain Example:

Write a JavaScript function that uses a chain of .then() calls to perform a series of asynchronous tasks.

Solution-1:

Code:

// Define a function that returns a Promise
function performTask(taskName, delay) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(`${taskName} completed`);
    }, delay); // Simulate task delay
  });
}

// Chain of asynchronous tasks
performTask("Task 1", 1000) // First task takes 1 second
  .then((result1) => {
    console.log(result1); // Logs "Task 1 completed"
    return performTask("Task 2", 2000); // Second task takes 2 seconds
  })
  .then((result2) => {
    console.log(result2); // Logs "Task 2 completed"
    return performTask("Task 3", 1500); // Third task takes 1.5 seconds
  })
  .then((result3) => {
    console.log(result3); // Logs "Task 3 completed"
    console.log("All tasks completed!");
  });

Output:

"Task 1 completed"
"Task 2 completed"
"Task 3 completed"
"All tasks completed!"

Explanation:

  • The performTask function simulates an asynchronous task using setTimeout and returns a Promise.
  • A chain of .then() calls is used to execute tasks in sequence.
  • Each .then() returns a new Promise, which is resolved after the current task completes.
  • Results from each task are logged in sequence.

Solution-2: Modular Promise Chain with Helper Function

Code:

// Define a helper function that executes tasks in a chain
function chainTasks(tasks) {
  let chain = Promise.resolve(); // Start with a resolved Promise
  tasks.forEach(([taskName, delay]) => {
    chain = chain.then(() => {
      return performTask(taskName, delay); // Chain the next task
    }).then((result) => {
      console.log(result); // Log the result of the task
    });
  });
}

// Use the previously defined performTask function
function performTask(taskName, delay) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(`${taskName} completed`);
    }, delay); // Simulate task delay
  });
}

// Define a list of tasks with delays
const tasks = [
  ["Task 1", 1000], // 1-second delay
  ["Task 2", 2000], // 2-second delay
  ["Task 3", 1500], // 1.5-second delay
];

// Execute the tasks in sequence
chainTasks(tasks); 

Output:

"Task 1 completed"
"Task 2 completed"
"Task 3 completed"

Explanation:

  • The chainTasks function accepts an array of tasks, each represented by a task name and delay.
  • The function initializes a resolved Promise (Promise.resolve()) and chains each task using .then().
  • The performTask function is used to simulate the asynchronous task execution.
  • Results from each task are logged as they complete.

See the Pen promises-and-async-await-exercise-2 by w3resource (@w3resource) on CodePen.


For more Practice: Solve these Related Problems:

  • Write a JavaScript function that chains multiple .then() calls where each step appends a new string to the result.
  • Write a JavaScript function that chains Promises to perform sequential arithmetic operations on an initial value.
  • Write a JavaScript function that simulates a multi-step asynchronous data transformation using chained Promises.
  • Write a JavaScript function that chains API calls, where the output of one Promise feeds into the next in the chain.

Go to:


PREV : Create a Simple Promise
NEXT :Handling Promise Rejection.

Improve this sample solution and post your code through Disqus

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.