promises-chain v2
by Roman Fedytskyi
JavaScript
const urls = new Array(10).fill('').map((item, i) => `https://jsonplaceholder.typicode.com/posts/${++i}`);
/* Solutions via reduce */
const makeRequestsChain = () => {
urls.reduce((accum, item) =>
accum.then(() => fetch(item)), Promise.resolve());
};
/* Solutions via reduce with delay */
const makeRequestsChainWithDelay = (delay = 3000) => {
urls.reduce((accum, item) =>
accum.then(() => new Promise(resolve => {
setTimeout(() => {
fetch(item);
resolve();
}, delay);
})), Promise.resolve());
};
/* Solutions via reduce with passing arguments */
const makeRequestsChainWithPassingArguments = () => {
const getJson = data => data.json();
// TODO: this log function exists only for presentation. It shows ability to put data from the prev request to the next one
const log = data => console.error('data', data);
const initState = Promise.resolve(new Response(JSON.stringify({})));
urls.reduce((accum, item) =>
accum
.then(getJson)
.then(log)
.then(fetch.bind(null, item)), initState)
.then(getJson)
.then(log)
};
/* Solution via recursion*/
const makeRequestsChainViaReqursion = () => {
const makeRequests = urls => {
const url = urls.shift();
if (url) {
fetch(url).then(() => makeRequests(urls))
}
};
makeRequests(urls);
};
/* Solution via async/await */
function chainPromisesViaAsync() {
const promises = urls.map(async url => {
const result = await fetch(url);
return result;
});
Promise.all(promises).then(data => {
console.error('data', data);
});
}