Run Promises in Series

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will be exploring how to run an array of promises in series using JavaScript. We will be using the Array.prototype.reduce() method to create a promise chain, where each promise returns the next promise when resolved. By the end of this lab, you will have a better understanding of how to execute promises sequentially, taking your programming skills to the next level.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/AdvancedConceptsGroup -.-> javascript/async_prog("`Asynchronous Programming`") javascript/AdvancedConceptsGroup -.-> javascript/higher_funcs("`Higher-Order Functions`") subgraph Lab Skills javascript/variables -.-> lab-28607{{"`Run Promises in Series`"}} javascript/data_types -.-> lab-28607{{"`Run Promises in Series`"}} javascript/arith_ops -.-> lab-28607{{"`Run Promises in Series`"}} javascript/comp_ops -.-> lab-28607{{"`Run Promises in Series`"}} javascript/async_prog -.-> lab-28607{{"`Run Promises in Series`"}} javascript/higher_funcs -.-> lab-28607{{"`Run Promises in Series`"}} end

Running Promises in a Series

To execute an array of promises in a series, use Array.prototype.reduce() to create a promise chain. Each promise returns the next promise after being resolved.

To start, open the Terminal/SSH and type node to begin practicing coding.

Here's an example of the code:

const runPromisesInSeries = (ps) =>
  ps.reduce((p, next) => p.then(next), Promise.resolve());

You can then use the runPromisesInSeries function to execute promises sequentially, as shown in the following example:

const delay = (d) => new Promise((r) => setTimeout(r, d));
runPromisesInSeries([() => delay(1000), () => delay(2000)]);
// This code runs each promise sequentially, taking a total of 3 seconds to complete.

Summary

Congratulations! You have completed the Run Promises in Series lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like