用axios递归获取数据并链接结果 [英] Recursively fetching data with axios and chaining the result
问题描述
我的网址格式为 http://www.data.com/1
,其中末尾的1可以运行直到出现未预定义的数字.它返回一个数组.我需要将所有合并为一个的数组连接起来.
I have an url of the pattern http://www.data.com/1
, where the 1 at the end can run up until a not predefined number. It returns an array. I need to concatenate all the arrays I get into one.
我的策略是递归执行get-request,直到出现404错误,然后返回结果.
My strategy is to recursively perform a get-request, until I get a 404 error, upon which I return the result.
var returnArray = [];
function getData(count){
let p = axios.get(`http://www.data.com/${count}`).then(function(response){
returnArray = returnArray.concat(response.data);
return getData(count +1);
}
).catch(function() {
Promise.resolve(returnArray);
}
)};
但是,当我实现此功能时,我的结果是不确定的.
When I implement this function, however, my result is undefined.
getData(1).then((response) => console.log(response))
做到这一点的最佳方法是什么?
What is the best way to do this?
推荐答案
在 getData
内部,您没有返回诺言,因此该函数会立即以未定义的值退出.因此,代替:
Inside getData
, you are not returning the promise, so the function immediately exits with undefined value.
So, instead of:
let p = axios.get(`http://www.data.com/${count}`).then(function(response){
使用:
return axios.get(`http://www.data.com/${count}`).then(function(response){
正如Bergi所指出的那样,您还需要在 catch
处理程序中返回 returnArray
,因此,代替:
As Bergi pointed out, you also need to return returnArray
within catch
handler, so instead of:
Promise.resolve(returnArray);
使用:
return returnArray;
这是完整的代码:
var returnArray = [];
function getData(count){
return axios.get(`http://www.data.com/${count}`).then(function(response){
returnArray = returnArray.concat(response.data);
return getData(count +1);
}
).catch(function() {
return returnArray;
}
)};
这篇关于用axios递归获取数据并链接结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!