递归调用api(axios / javascript)

时间:2017-11-03 15:07:58

标签: javascript recursion ecmascript-6 es6-promise axios

我尝试使用递归来填充数组,其中包含多个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"

1 个答案:

答案 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
});