使用 axios 递归获取数据并链接结果 [英] Recursively fetching data with axios and chaining the result
问题描述
我有一个 http://www.data.com/1
模式的 url,其中末尾的 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))
最好的方法是什么?
推荐答案
在 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屋!