Estoy tratando de enviar múltiples PUT al mismo punto final, pero necesito hacerlo uno a la vez DESPUÉS de que se complete el anterior.
Mis datos son una matriz que mapeo y envío cada uno, podría ser solo 1 o 100 ... El punto final es una función lambda pero no puede manejar el envío a todos a la vez ...
¿Alguien puede sugerir una manera de hacer esto?
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); }); })); }Puede usar un ciclo para revisar todas las solicitudes con async/await para esperar una respuesta en lugar de 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 } }En lugar de crear una matriz de promesas, es posible que desee crear una matriz de funciones que devuelvan promesas para ejecutarlas secuencialmente. ¡Aquí hay una solución realmente genial y limpia que podría ayudar! https://stackoverflow.com/a/43082995/8222441