递归调用api(axios/javascript)
我试图用使用递归的多个API调用的结果填充数组。我对ES6和递归之类的东西已经有些不知所措了,可能需要一些帮助 这是我当前的代码,它只返回“承诺”:递归调用api(axios/javascript),javascript,recursion,ecmascript-6,es6-promise,axios,Javascript,Recursion,Ecmascript 6,Es6 Promise,Axios,我试图用使用递归的多个API调用的结果填充数组。我对ES6和递归之类的东西已经有些不知所措了,可能需要一些帮助 这是我当前的代码,它只返回“承诺”: 要访问从承诺解析的值,必须使用承诺的。然后方法。因此,代替此分配,this.allEmployees=this.getAllEmployees()从getAllEmployees访问解析值,如下所示: this.getAllEmployees() .then(employees => { console.log(employees);
要访问从承诺解析的值,必须使用承诺的
。然后方法。因此,代替此分配,this.allEmployees=this.getAllEmployees()代码>从getAllEmployees
访问解析值,如下所示:
this.getAllEmployees()
.then(employees => {
console.log(employees); // make sure this is what you need
this.allEmployees = employees;
});
编辑:回复评论
函数getAllEmployees
返回gethoseEmployees
的值,这是一个承诺。因为当最终返回时,allEmployees
在的匿名函数中。然后,
,该值将始终是gethoseemployees
返回的承诺的内部值
// This functions return value is a promise
const getData = () => {
return axios.get('some-url')
.then(data => {
// Anything returned inside of a .then will be
// resolved and can only be accessed with another .then.
// Using .then itself will return another promise object,
// which is why promises can be chained.
return formatThisData(data);
});
};
为了从getData
访问我想要的格式化数据,我必须从promise访问解析的数据
getData()
.then(formattedData => {
// formattedData is what was returned from inside the .then above
});
函数可能重复,但函数最终不会返回allEmployees的值吗?按照我的想法,gethoseEmployees()将调用自己,直到else语句返回allEmployees数组。我将Dominics answer标记为正确,因为它确实回答了我的问题并让我明白了。然而,我正在阅读建议的副本(长线程),我相信它将进一步澄清它。不确定我是否应该选中“这解决了我的问题”按钮?
getData()
.then(formattedData => {
// formattedData is what was returned from inside the .then above
});