簡體   English   中英

如何在 HTTP 請求中放置緩沖區?

[英]How to put a buffer in an HTTP request?

我試圖在請求中放置一個緩沖區,因為我有一個要導入的數據列表。 我想要一個接一個的成功請求。 我遇到的問題是它等待上傳請求的所有數據。

這是示例數據:

[
  {
    "contacts": "dsds@dsd.com",
    "recipient": "dsd@dsd.com",
    "date_sent": "07/08/2020 17:05:04",
    "subject": "repurchase"
  },
  {
    "contacts": "asd@ret.com",
    "recipient": "test@yahoo.com",
    "date_sent": "07/10/2020 17:31:51",
    "subject": "biz"
  },
  {
    "contacts": "we@sdf.com",
    "recipient": "abc@yahoo.com",
    "date_sent": "07/09/2020 13:02:54",
    "subject": "rock"
  }
];
const createEngage = async(body) => {
  const BASE_URL = '/api/import'
  var requestOptions = {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        "Content-Type": "application/json"
      },
      body: body
    };

  fetch(BASE_URL, requestOptions)
    .then(response => response.text())
    .then(async result => {
      console.log(result);
    })
    .catch(error => console.log('error', error));
}

您可能想要做的是遍歷您的數據並使用async / await在每次迭代時等待。 您的異步函數的實現目前不await任何東西。 相反,它應該使用response.text() await fetch請求和正文的解碼。

檢查響應是否有錯誤並將fetch請求包裝在try...catch塊中。 如果發生錯誤,則將執行catch塊。 否則,請檢查response對象是否有您想要包含的任何狀態或錯誤。

const data = [
  {
    "contacts": "dsds@dsd.com",
    "recipient": "dsd@dsd.com",
    "date_sent": "07/08/2020 17:05:04",
    "subject": "repurchase"
  },
  {
    "contacts": "asd@ret.com",
    "recipient": "test@yahoo.com",
    "date_sent": "07/10/2020 17:31:51",
    "subject": "biz"
  },
  {
    "contacts": "we@sdf.com",
    "recipient": "abc@yahoo.com",
    "date_sent": "07/09/2020 13:02:54",
    "subject": "rock"
  }
];
const BASE_URL = '/api/import'

/**
 * Sends a request for each individual item.
 */
const createEngage = async body => {
  const requestOptions = {
    method: 'POST',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    },
    body
  };
  try {
    const response = await fetch(BASE_URL, requestOptions);
    if (!response.ok) {
      alert('Your request has failed');
      return null;
    }
    const text = await response.text();
    return text;
  } catch(error) {
    alert('Your request caused an error');
  }
};

/**
 * Loop over each item and call createEngage.
 * Wait for the request to finish and continue.
 */
const createMultipleEngages = async data => {
  for (const item of data) {
    const result = await createEngage(item); // This will make the loop wait every time.
    console.log(result);
  }
};

// Call the function and start looping.
createMultipleEngages(data);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM