Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

100
Visualizações
How to do multiple fetches to a single endpoint when previous has completed

I am trying to send multiple PUT's to the same endpoint but need to do them one at a time AFTER the previous one completed..

My data is an Array which I map over and send each one, it could be just 1 or a 100.. The endpoint is a lambda function but can't handle sending to it all at once..

Can anyone suggest a way to do this?

function sendData(data: any) {

type NewContact = {
  contact_type: number;
  contact_code: [];
  contact_type_desc: string;
  changed_by: string;
};
console.log('Array: ', data);
const headers = {
  "x-api-key": env['x-api-key'],
};

const endpoint = env['contact_types'](studentId);

const rst = Promise.all( data.map((newContactType: NewContact) => {
    return fetch(endpoint, {
      method: 'PUT',
      headers: headers,
      body: JSON.stringify(newContactType)
    })
    .then((response) => {
      console.log('Respose: ', response);
      if (response.ok) {
        return response.json();
      } else {
        throw new Error('Network response was not ok.');
      }
    })
    .catch((error) => {
      console.log('There has been a problem with your fetch operation: ' + error.message);
    });
}));
}
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You can use a loop to go through all requests with async/await for waiting one by one response instead of Promise.all

async function sendData(data: any) {

   type NewContact = {
     contact_type: number;
     contact_code: [];
     contact_type_desc: string;
     changed_by: string;
   };
   console.log('Array: ', data);
   const headers = {
     "x-api-key": env['x-api-key'],
   };

   const endpoint = env['contact_types'](studentId);

   //this function will return a promise
   const fetchDataByContactType = (newContactType: NewContact) => {
    return fetch(endpoint, {
      method: 'PUT',
      headers: headers,
      body: JSON.stringify(newContactType)
    })
    .then((response) => {
      console.log('Respose: ', response);
      if (response.ok) {
        return response.json();
      } else {
        throw new Error('Network response was not ok.');
      }
    })
    .catch((error) => {
      console.log('There has been a problem with your fetch operation: ' + 
     error.message);
   })
  }

   const rst = []

   for(const newContactType of data) {
      //wait for response from promise
      const response = await fetchDataByContactType(newContactType)
      rst.push(response) //push your response to the result list `rst`
      //TODO: You can do anything else with your response here
   }
}
about 4 years ago · Juan Pablo Isaza Relatório

0

Instead of creating an array of promises, you might want to create an array of functions that return promises to execute them sequentially. There is a really great and clean solution here that might help! https://stackoverflow.com/a/43082995/8222441

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda