Dennis
Dennis

Reputation: 1156

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

Upvotes: 0

Views: 119

Answers (2)

Nick Vu
Nick Vu

Reputation: 15540

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
   }
}

Upvotes: 2

Amit Maraj
Amit Maraj

Reputation: 374

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

Upvotes: 0

Related Questions