I was reading this article HERE, which speaks about how can you use reduce with promises and in the end the following snippet is shown:
const tasks = getTaskArray();
return tasks.reduce((promiseChain, currentTask) => {
return promiseChain.then(chainResults =>
currentTask.then(currentResult =>
[ ...chainResults, currentResult ]
)
);
}, Promise.resolve([])).then(arrayOfResults => {
// Do something with all results
});
So without changing much of the code , i made the following demo:
const tasks = [ fetch('https://jsonplaceholder.typicode.com/todos/1') ,
fetch('https://jsonplaceholder.typicode.com/todos/2') ,
fetch('https://jsonplaceholder.typicode.com/todos/3') ];
tasks.reduce((promiseChain, currentTask) => {
console.log(promiseChain);
return promiseChain.then(chainResults => {
return currentTask.then(currentResult =>
[ ...chainResults, currentResult ]
)
});
}, Promise.resolve([])).then(arrayOfResults => {
// Do something with all results
console.log(arrayOfResults);
});
But i still don't understand , since reduce is simplistically just a forEach loop and inside reduce we are relying on a promise being returned, what is the guareenty that the reduce function will not just loop though all the elements in the array (in this case an array of promises) , without the then() firing ?