Replace the use of forEach
with a reduce
, and include .then()
.
The code below will keep track of the promise from the last fetch
in acc
(the accumulator parameter of reduce
). It appends the new fetch
inside a then
listener to ensure the previous fetch
is completed:
const teams = ['LFC', 'MUFC', 'CFC'];
teams.reduce((acc, team) => {
return acc.then(() => {
return fetch({
url: URL,
method: 'PUT',
body: team
});
})
}, Promise.resolve())
.then(() => console.log("Everything's finished"))
.catch(err => console.error("Something failed:", err))
//Simulate fetch:
const fetch = team => new Promise(rs => setTimeout(() => {rs();console.log(team)}, 1000))
const teams = ['LFC', 'MUFC', 'CFC'];
teams.reduce((acc, team) => {
return acc.then(() => {
return fetch({
url: URL,
method: 'PUT',
body: team
});
})
}, Promise.resolve())
.then(() => console.log("Everything's finished"))
.catch(err => console.error("Something failed:", err))
You have the option to create a general helper function for this approach:
const teams = ['LFC', 'MUFC', 'CFC'];
const promiseSeries = (arr, cb) => arr.reduce((acc, elem) => acc.then(() => cb(elem)), Promise.resolve())
promiseSeries(teams, (team) => {
return fetch({
url: URL,
method: 'PUT',
body: team
})
})
.then(() => console.log("Everything's finished"))
.catch(err => console.error("Something failed:", err))
//Simulate fetch:
const fetch = team => new Promise(rs => setTimeout(() => {rs();console.log(team)}, 1000))
const teams = ['LFC', 'MUFC', 'CFC'];
const promiseSeries = (arr, cb) => arr.reduce((acc, elem) => acc.then(() => cb(elem)), Promise.resolve())
promiseSeries(teams, (team) => {
return fetch({
url: URL,
method: 'PUT',
body: team
})
})
.then(() => console.log("Everything's finished"))
.catch(err => console.error("Something failed:", err))
Alternatively, if you are able to (ES2017), utilizing async/await
is recommended for improved readability:
const teams = ['LFC', 'MUFC', 'CFC'];
async function upload(teams){
for(const team of teams){
await fetch({
url: URL,
method: 'PUT',
body: team
});
}
}
upload(teams)
.then(() => console.log("Everything's finished"))
.catch(err => console.error("Something failed:", err))
//Simulate fetch:
const fetch = team => new Promise(rs => setTimeout(() => {rs();console.log(team)}, 1000))
const teams = ['LFC', 'MUFC', 'CFC'];
async function upload(teams) {
for (const team of teams) {
await fetch({
url: URL,
method: 'PUT',
body: team
});
}
}
upload(teams)
.then(() => console.log("Everything's finished"))
.catch(err => console.error("Something failed:", err))