w3resource

Sequential Asynchronous tasks with Async/Await in JavaScript


Chained Async/Await Example:

Write a JavaScript program that uses async/await to perform three asynchronous tasks in sequence.

Solution-1: Using async/await with Separate Functions

Code:

// Function to simulate an asynchronous task
const asyncTask = (taskName, time) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log(`${taskName} completed`);
      resolve(taskName);
    }, time);
  });
};

// Function to execute tasks in sequence using async/await
const executeTasks = async () => {
  const result1 = await asyncTask("Task 1", 1000); // Wait for Task 1
  console.log(result1);

  const result2 = await asyncTask("Task 2", 2000); // Wait for Task 2
  console.log(result2);

  const result3 = await asyncTask("Task 3", 1500); // Wait for Task 3
  console.log(result3);

  console.log("All tasks completed sequentially");
};

// Execute the function
executeTasks();

Output:

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

Explanation:

  • asyncTask is a function that returns a Promise simulating a delayed task using setTimeout.
  • The executeTasks function:
    • Uses await to wait for each task to complete before starting the next.
    • Logs the result of each task sequentially.
  • The execution ensures tasks run one after the other, making the process easy to follow.

Solution-2: Using async/await with an Array of Tasks

Code:

// Function to simulate an asynchronous task
const asyncTask = (taskName, time) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log(`${taskName} completed`);
      resolve(taskName);
    }, time);
  });
};

// Array of task definitions
const tasks = [
  () => asyncTask("Task 1", 1000),
  () => asyncTask("Task 2", 2000),
  () => asyncTask("Task 3", 1500),
];

// Function to execute tasks in sequence using async/await
const executeTasksSequentially = async (tasks) => {
  for (const task of tasks) {
    const result = await task(); // Wait for each task to complete
    console.log(result);
  }
  console.log("All tasks completed sequentially");
};

// Execute the tasks
executeTasksSequentially(tasks);

Output:

"Task 1 completed"
"Task 1"
"All tasks completed sequentially"

Explanation:

  • asyncTask is reused to simulate asynchronous tasks.
  • Tasks are stored as functions in an array.
  • executeTasksSequentially iterates over the array using a for...of loop and waits for each task to complete with await.
  • Results are logged sequentially, and a final message indicates completion.

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


For more Practice: Solve these Related Problems:

  • Write a JavaScript function using async/await that chains multiple API calls where each call depends on the previous response.
  • Write a JavaScript function using async/await that processes an array of asynchronous tasks sequentially and logs each result.
  • Write a JavaScript function using async/await that performs several data transformation steps in sequence, awaiting each one.
  • Write a JavaScript function using async/await that simulates a multi-step user registration process with sequential asynchronous validations.

Go to:


PREV : Simulating a Task Queue.
NEXT : Error Handling in Async/Await.

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.