[英]Trying to loop axios requests and push it asynchronously
async function getData() {
let getProject =
await axios.get('url', {
auth: {
username: 'username',
password: 'pw'
}
})
let projects = await getProject.data.value;
let arr = []
projects.map(project => {
let item = axios.get(`url`, {
auth: {
username: 'username',
password: 'pw'
}
})
arr.push(item)
console.log('arr', arr)
})
let result = await axios.all(arr)
console.log('pr', result)
return arr;
}
In the getProject
I get the object of the projects by calling the API.在
getProject
我通过调用 API 获取项目的对象。 Then I try to loop through these fetched objects and use unique url for each project to call another API in projects.map
.然后我尝试遍历这些获取的对象,并为每个项目使用唯一的 url 来调用
projects.map
另一个 API。
console.log('arr', arr)
gives me the array of Promises, and some of them are failed requests and some of them are successful. console.log('arr', arr)
给了我console.log('arr', arr)
的数组,其中一些是失败的请求,一些是成功的。 This is intended because some projects might not have the valid API.这是因为某些项目可能没有有效的 API。 But I will want an array with successful Promises.
但我想要一个具有成功 Promise 的数组。
This doesn't even reach the line console.log('pr' result)
and I am not sure why.这甚至没有到达
console.log('pr' result)
,我不知道为什么。
Am I doing it right?我做得对吗?
Try revising your code so that arr
is an array of functions that return promises for axio requests (rather than arr
being an array of actual axios request promises, as you are currently doing):尝试修改您的代码,以便
arr
是一个返回 axio 请求承诺的函数数组(而不是arr
是一个实际的 axios 请求承诺数组,正如您目前所做的那样):
let projects = await getProject.data.value;
// Map all project items to functions that return promises
let arr = projects.map(project => {
// Return a function that returns a promise
return function() {
// Returns a promise for GET request
return axios.get(`url`, {
auth: {
username: 'username',
password: 'pw'
}
})
}
})
// Axios.all will concurrently perform all GET requests
// in arr (ie the mapping of projects to functions that
// return promises from axios.get )
let result = await axios.all(arr)
// Should print results from axio.get (if all requests successful)
console.log('pr', result)
This is a subtlty with the way methods like axios.all
typically work and is similar to the native Promise.all
method.这是 axios.all 等方法通常工作方式的
axios.all
,类似于原生的Promise.all
方法。 For more information see the example just above "axios API" in the axios docs有关更多信息,请参阅axios 文档中“axios API”上方的示例
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.