我有一个模式 http://www.data.com/1
的 url,其中末尾的 1 可以一直运行到一个未预定义的数字。它返回一个数组。我需要将我得到的所有数组连接成一个。
我的策略是递归地执行 get-request,直到收到 404 错误,然后返回结果。
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);
}
)};
但是,当我实现此函数时,我的结果是未定义的。
getData(1).then((response) => console.log(response))
最好的方法是什么?
最佳答案
在getData
内,您没有返回promise,因此函数立即退出并返回未定义的值。
所以,而不是:
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
,因此不要:
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;
}
)};
关于javascript - 使用 axios 递归获取数据并链接结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49839831/