javascript async fetch function

Tags: , ,



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()});
  }
}

Answer

This is the correct code for async for..of loop

async function fetchArchive(arr,state,mailbox){
    console.log(1)
  if(arr.length === 0){
    load_mailbox(mailbox)
  }
    
  for await (const elem of arr){
    await fetch2(elem);
        arr.shift();

        console.log({ elem })

    fetchArchive(arr,state,mailbox)
  }
}

However, this code does not work and causes infinity recursion 🙂 I think it is bad idea to mutate the array inside iteration. Also, please keep in mind, that then receives callback. So, the propper argument for then is:

.then(response=>fetchArchive(respone))

In your case, you can’t pass fetchArchive as an argument to then method because fetchArchive does not return function

[UPDATE]

This is the working code with array index comparison:

const fetchArchive = async (a, s, callback) => {
  for (const [index, value] of a.entries()) {
    await fetch(index)
      // if i is the last item, load mailbox
      .then(() => {
        if (index == a.length - 1 && callback) {
          callback();
        }
      });
  }
};

Documentation about entries U can find here



Source: stackoverflow