上一个完成后如何对单个端点进行多次提取

How to do multiple fetches to a single endpoint when previous has completed

我正在尝试将多个 PUT 发送到同一个端点,但需要在前一个完成后一次发送一个。

我的数据是一个数组,我将其映射并发送每个数据,它可能只是 1 或 100.. 端点是一个 lambda 函数,但无法一次处理发送给它的所有数据..

任何人都可以建议一种方法吗?

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

您可能想要创建一个 return 承诺按顺序执行的函数数组,而不是创建一个承诺数组。这里有一个非常棒且干净的解决方案可能会有所帮助!

您可以使用循环遍历所有请求 async/await 等待一个一个的响应而不是 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
   }
}