w3resource

JavaScript: Run a given array of promises in series

JavaScript fundamental (ES6 Syntax): Exercise-150 with Solution

Write a JavaScript program to run a given array of promises in series.

  • Use Array.prototype.reduce() to create a promise chain, where each promise returns the next promise when resolved.

Sample Solution:

JavaScript Code:

//#Source https://bit.ly/2neWfJ2

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

// Define a delay function that returns a promise resolving after a specified time
const delay = d => new Promise(r => setTimeout(r, d));

// Executes each promise sequentially, taking a total of 3 seconds to complete
runPromisesInSeries([() => delay(1000), () => delay(2000)]);

Flowchart:

flowchart: Run an given array of  promises in series

Improve this sample solution and post your code through Disqus

Previous: Write a JavaScript program to get a random element from an array.
Next: Write a JavaScript program to run a function in a separate thread by using a Web Worker, allowing long running functions to not block the UI.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/javascript-exercises/fundamental/javascript-fundamental-exercise-150.php