我有一个使用axios的功能,其中我将根据为特定用户返回的ID数量删除多个记录。
async function DeleteAllRecords (emailAddress) {
try {
var accessToken = await setup.getAccessToken(emailAddress);
var userId = await user.getUserId(emailAddress);
var recordIds = await getAllRecordID(emailAddress);
console.log(`Deleting all records for `+emailAddress+``);
for (const rId of recordIds) {
const response = await axios.delete(`${process.env.API_URL}/`+userId+`/records/`+recordIds+``, {'headers': {Authorization: 'Bearer '+accessToken+''}});
}
return response;
}
catch(e) {
console.error(``+emailAddress+` produced the Record Delete Error = ` + e);
}
}
这不起作用,我不确定为什么。我希望看到每个axios.delete调用的响应,但是我不确定如何获得该响应。当前其返回为undefined。
答案 0 :(得分:4)
为什么您的代码不起作用:
const response
在循环作用域内声明,无法从此闭包中访问。 let const
,并在循环内分配的,您仍然仍然只能返回最后一个响应。您可以将每个响应推送到一个数组(responses
),然后返回该数组:
async function DeleteAllRecords (emailAddress) {
try {
var accessToken = await setup.getAccessToken(emailAddress);
var userId = await user.getUserId(emailAddress);
var recordIds = await getAllRecordID(emailAddress);
console.log(`Deleting all records for `+emailAddress+``);
const responses = [];
for (const rId of recordIds) {
const response = await axios.delete(`${process.env.API_URL}/`+userId+`/records/`+recordIds+``, {'headers': {Authorization: 'Bearer '+accessToken+''}});
responses.push(response);
}
return responses;
}
catch(e) {
console.error(``+emailAddress+` produced the Record Delete Error = ` + e);
}
}
但是,在这种情况下,多个并行请求会更好,因为您实际上不需要一一删除。我将使用Array.map()
迭代recordIds
数组,并为每个数组返回一个promise,然后使用Promise.all()
等待所有响应,这还将返回一个响应数组:
async function DeleteAllRecords (emailAddress) {
try {
var accessToken = await setup.getAccessToken(emailAddress);
var userId = await user.getUserId(emailAddress);
var recordIds = await getAllRecordID(emailAddress);
console.log(`Deleting all records for `+emailAddress+``);
return Promise.all(recordIds.map(rId => axios.delete(`${process.env.API_URL}/`+userId+`/records/`+recordIds+``, {'headers': {Authorization: 'Bearer '+accessToken+''}})));
}
catch(e) {
console.error(``+emailAddress+` produced the Record Delete Error = ` + e);
}
}
答案 1 :(得分:0)
这不起作用,我不确定为什么。我希望看到每个axios.delete调用的响应,但是我不确定如何获得该响应。目前,其返回的响应尚未定义。
您的代码中存在几个问题:
const response
在循环块中声明,但是您尝试在循环后返回它。 const
和let
严格受块范围限制,因此在循环块基本上告诉JS返回未定义的变量之后,通过引用response
。response
。如果没有解决上述问题,则仍然无法正常工作,因为您只会得到最后一次循环运行的响应。在这里,您必须收集所有运行的响应,例如进入列表。