Search code examples
javascriptrecursionecmascript-6es6-promiseaxios

Recursively call api (axios / javascript)


I'm trying to fill an array with the result of multiple API calls using recursion. I'm pretty over my head here with ES6 and the recursion stuff and could need some help.

Here is my current code, which only returns "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"

Solution

  • To access value resolved from a promise you must use the Promise's .then method. So instead of this assignment, this.allEmployees = this.getAllEmployees(); access the resolved value from getAllEmployees like so:

    this.getAllEmployees()
    .then(employees => {
        console.log(employees); // make sure this is what you need
        this.allEmployees = employees;
    });
    

    EDIT: Reply to comment.

    Your function getAllEmployees returns the value of getThoseEmployees, which is a promise. Because allEmployees, when eventually returned, is inside of the anonymous function of the .then, that value will always be internal to the promise returned by 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);
        });
    };
    

    In order to access the formatted data I want from getData, I have to access the resolved data from the promise.

    getData()
    .then(formattedData => {
        // formattedData is what was returned from inside the .then above
    });