I am trying to create a recursive function that sends a PUT request for every integer of a given array, and call another function at the end of it.
function fetchArchive(arr,state,mailbox){
if(arr.length == 0){
load_mailbox(mailbox)
}
for(i of arr){
fetch(`/emails/${arr.shift()}`, {
method: 'PUT',
body: JSON.stringify({
archived: state
})
})
.then(fetchArchive(arr,state,mailbox))
}
}
But it seems that it calls the load_mailbox() function before fetching the last item of the array.
I know that this should be better implemented using async / await. Can someone give an example of that to help me understand?
UPDATE: It turns out that the code below is working
async function fetchArchive(a,s,callback){
for(i of a){
await fetch(`/emails/${i}`, {
method: 'PUT',
body: JSON.stringify({
archived: s
})
})
// if i is the last item, load mailbox
.then(() => { if(i==a[a.length-1] && callback) callback()});
}
}