【发布时间】:2021-06-21 22:07:52
【问题描述】:
我有一个函数,我想为学生返回所有即将完成的作业。我首先运行另一个异步函数,该函数返回学生在一个学期和一年内的所有课程 ID。然后我用每个类的 .get url 填充一个数组。
我的问题是理解和使用Axios.all(),因为我想对每个班级进行多次调用,然后对每个作业进行排序,只保存迟于学生当前日期的作业。我面临的问题是axios.all([urls]) 返回UnhandledPromiseRejectionWarning: Error: Request failed with status code 401。我不知道为什么我不能从每个 url 调用中返回正确的数据。我把它缩小到我如何设置我的 axios.all 调用的问题。有人能指出我正确的方向吗?
//Get all upcoming assignments from each class for a user
async function getAssignments(){
//Make multiple requests to api
axios
.all([urls])
//Loop through each assignment for each class
.then(
axios.spread((...res) =>{
for (var i = 0; i < res.data.length; i++) {
//If the due date of the assignment is due later than the users current date, push to array
if (res.data[i]['due_at'] > date.toISOString()) {
assignments.push(res.data[i])
}
}
//Output all assignments
return assignments
})
)
}
更新:
我忘记将令牌传递给我的标头,经过更多调整后,它现在将从我的数组中获取指定的 url。但我现在需要它来抓取数组中的每个 url 并同时进行调用。虽然我有点难过,但我是否只需要为.get 或更具体的东西创建一个 for 循环?有人能指出我正确的方向吗?
//urls is the array filled with links. Need for the axios calls to happen concurrently
axios.all([axios.get(
urls[0],
{
headers: {
Authorization: `Bearer ${token}`,
},
}
)])
//Loop through each assignment in a specfied class in canvas
.then(
axios.spread((...res) =>{
for (var i = 0; i < res[0].data.length; i++) {
//If the due date of the assignment is due later than the users current date, push to array
if (res[0].data[i]['due_at'] > date.toISOString()) {
assignments.push(res[0].data[i])
}
}
console.log(assignments)
})
)
.catch((err) => console.log(err))
【问题讨论】:
-
代码看起来正确并且应该可以工作,您面临的问题是什么。你需要更具体
-
@Sohan 我面临的问题是 axios.all([urls]) 返回
UnhandledPromiseRejectionWarning: Error: Request failed with status code 401。我无法弄清楚为什么我不能从每个 url 调用中返回正确的数据。我将其缩小为我如何设置axios.all呼叫的问题。 -
它是
401。看起来远程端点是安全的,并且您没有在Authorization标头中传递有效令牌?请先验证一下?还要用您遇到的错误更新您的问题。它提供了更多上下文 -
@Sohan 这是我忘记添加到通话中的内容。感谢您注意到这一点!我现在只需要让
axios.all获取数组中的每个链接。我会根据我的问题更新我的帖子。
标签: javascript arrays promise axios