我尝试使用递归来填充数组,其中包含多个API调用的结果。我非常喜欢ES6和递归的东西,可能需要一些帮助。
这是我当前的代码,它只返回" promise" :
getAllEmployees: function() {
let allEmployees = []; // this array will contain all employees
let pageNumber = 1; // start with page 1
const getThoseEmployees = function(pageNumber) {
return axios.get(rest_url + 'users/?per_page=50&page=' + pageNumber, {
headers: {
'X-WP-Nonce': WPsettings.nonce
},
}).then(response => {
// add the employees of this response to the array
allEmployees = allEmployees.concat(response.data);
pageNumber++;
if (response.headers['x-wp-total'] > allEmployees.length) {
// do me again...
return getThoseEmployees(pageNumber);
} else {
// this was the last page, return the collected contacts
return allEmployees;
}
});
}
return getThoseEmployees();
},
// after "created" in vue
this.allEmployees = this.getAllEmployees(); // returns "promise"
答案 0 :(得分:1)
要访问从承诺中解析的值,您必须使用Promise的.then
方法。因此,this.allEmployees = this.getAllEmployees();
代替此分配,从getAllEmployees
访问已解析的值,如下所示:
this.getAllEmployees()
.then(employees => {
console.log(employees); // make sure this is what you need
this.allEmployees = employees;
});
编辑:回复评论。
您的函数getAllEmployees
返回getThoseEmployees
的值,这是一个承诺。因为allEmployees
在最终返回时位于.then
的匿名函数内部,所以该值将始终位于getThoseEmployees
返回的承诺的内部。
// 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
访问我想要的格式化数据,我必须从承诺中访问已解析的数据。
getData()
.then(formattedData => {
// formattedData is what was returned from inside the .then above
});