[英]Multiple call of Axios.all requests from an array with multiple links
[英]Making multiple Axios get requests with an array of links?
我有一個 function,我想為學生返回所有即將完成的作業。 我首先運行另一個異步 function,它返回學生在一個學期和一年內的所有課程 ID。 然后我為每個 class 填充一個數組。
我的問題是理解和使用Axios.all()
,因為我想對每個 class 執行多次調用,然后對每個作業進行排序,只保存遲於學生當前日期的作業。 我面臨的問題是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
})
)
}
更新:我忘記向我的 header 傳遞一個令牌,經過更多調整后,它現在將從我的數組中獲取指定的 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))
您可以在最初在 axios 實例級別設置 header 假設您已經創建了 axios 實例,您可以簡單地,
const axios = require('axios');
axios.defaults.headers.common['Authorization'] = 'Bearer AUTH_TOKEN';
//Get the course ID for each class the user is assigned to
const courseID = await getCurrentCourses('Spring', '2021')
//Fill the array with urls to each course assignment page
for(let i = 0; i < courseID.length; i++){
urls.push(axios.get('https://example.com/api/v1/courses/' + allCourseID[i] + '/assignments'));
}
//Make multiple requests to api
axios.all(urls)
//Loop through each assignment for each class
.then({......});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.