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
const runPromisesInSeries = ps => ps.reduce((p, next) => p.then(next), Promise.resolve());
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:

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.
JavaScript: Tips of the Day
Chunks an array into n smaller arrays
Example:
const tips_chunkIntoN = (arr, n) => { const size = Math.ceil(arr.length / n); return Array.from({ length: n }, (v, i) => arr.slice(i * size, i * size + size) ); } console.log(tips_chunkIntoN([1, 2, 3, 4, 5, 6, 7,8], 4));
Output:
[[1,2],[3,4],[5,6],[7,8]]
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework