如何在HTTP请求中放入缓冲区



我试图在请求中放入缓冲区,因为我有一个要导入的数据列表。我想要一个接一个的成功请求。我遇到的问题是它等待上传请求的所有数据。

以下是示例数据:

[
{
"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任何内容。相反,它应该awaitfetch请求和用response.text()对主体的解码。

检查响应是否存在错误,并将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);

最新更新