Skip to content
Advertisement

Repeatedly await asynchronous post requests

I want to repeatedly do a POST request, as follows:

async function request(spec){
    // POST
    fetch('/spec', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            spec: spec
        })
    })
        .then(function(response){
            if(response.ok){
                console.log('POST success.');
                return;
            }
            throw new Error('POST failed.');
        })
        .catch(function(error){
            console.log(error);
        });
}
async function repeatRequest(times){
   for(let i=0; i<times; i++)
      await request("");
}

But this won’t work, because I’m somehow not using asynchronous programming correctly. Somehow even after spending hours on async js I don’t know if I still get it.

EDIT: this code is on the client-side.

Advertisement

Answer

To sequentially execute the request, you need to return the promise (return value of fetch) in the top level of your async function. This way the await keyword in the for loop will await the result of the function:

(Note that I have changed the target URL to have a running example here.)

async function request(pokemon) {
  return fetch('https://pokeapi.co/api/v2/pokemon/' + pokemon)
    .then((response) => {
      if (response.ok) {
        console.log('request success.');
        return;
      }
      throw new Error('request failed.');
    })
    .catch((error) => {
      console.log(error);
    });
}

async function repeatRequest(times) {
  for (let i = 0; i < times; i++) {
    console.log(i);
    await request("pikachu");
  }
}

repeatRequest(5);

Alternatively, you can use full async/await, like this:

async function request(pokemon) {
  try {
    let response = await fetch('https://pokeapi.co/api/v2/pokemon/' + pokemon);

    if (!response.ok) {
      throw new Error('request failed.');
    }
    
    console.log('request success.');
    return response;
  } catch (error) {
    console.log(error);
  }
}

async function repeatRequest(times) {
  for (let i = 0; i < times; i++) {
    console.log(i);
    await request("pikachu");
  }
}

repeatRequest(5);
Advertisement