我要在请求中放入缓冲区,因为我有要导入的数据列表。我想要一个接一个的成功请求。我遇到的问题是,它等待上载请求的所有数据。
以下是示例数据:
[
{
"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));
}
答案 0 :(得分:0)
您可能想做的是对数据进行循环,并使用async / await
等待每次迭代。当前,您对异步功能的实现没有await
任何东西。相反,它应该await
fetch
请求并使用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);