w3resource

Sequential Asynchronous task Processing in JavaScript


Simulating a Task Queue:

Write a JavaScript program that processes an array of asynchronous tasks sequentially using Promises.

Solution-1: Sequential Task Processing Using Promise.then()

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 tasks
const tasks = [
  () => asyncTask("Task 1", 1000),
  () => asyncTask("Task 2", 2000),
  () => asyncTask("Task 3", 1500),
];

// Process tasks sequentially using Promise.then()
const processTasksSequentially = (tasks) => {
  let promise = Promise.resolve();

  tasks.forEach((task) => {
    promise = promise.then(() => task());
  });

  return promise;
};

// Execute the tasks
processTasksSequentially(tasks).then(() => {
  console.log("All tasks completed sequentially");
});

Output:

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

Explanation:

  • asyncTask simulates an asynchronous operation using setTimeout.
  • The tasks array contains functions that return Promises.
  • The processTasksSequentially function:
    • Starts with an already-resolved Promise (Promise.resolve()).
    • Chains .then() for each task to ensure sequential execution.
  • Tasks are executed one after another, and a final message is logged once all tasks are completed.

Solution-2: Sequential Task Processing Using async/await

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 tasks
const tasks = [
  () => asyncTask("Task 1", 1000),
  () => asyncTask("Task 2", 2000),
  () => asyncTask("Task 3", 1500),
];

// Process tasks sequentially using async/await
const processTasksSequentially = async (tasks) => {
  for (const task of tasks) {
    await task(); // Wait for each task to complete before moving to the next
  }
  console.log("All tasks completed sequentially");
};

// Execute the tasks
processTasksSequentially(tasks);

Output:

"Task 1 completed"
"All tasks completed sequentially"

Explanation:

  • The asyncTask function remains the same.
  • The processTasksSequentially function uses a for...of loop to iterate over the tasks array.
  • await task() ensures each task completes before the next one starts.
  • The sequential nature of async/await simplifies readability and debugging.

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


Improve this sample solution and post your code through Disqus

Previous: Understanding Promise.allSettled in JavaScript.
Next: Sequential Asynchronous tasks with Async/Await in JavaScript.

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.