【问题标题】:Recursively call api (axios / javascript)递归调用api(axios/javascript)
【发布时间】:2017-11-03 15:07:58
【问题描述】:

我正在尝试使用递归将多个 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"

【问题讨论】:

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


【解决方案1】:

要访问从 Promise 解析的值,您必须使用 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 返回的promise 内部。

// 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 的值吗?按照我的想法,getThoseEmployees() 会调用自己,直到 else 语句返回 allEmployees-array。
  • 我将 Dominics 的答案标记为正确,因为它确实回答了我的问题并让我理解了。但是,我正在阅读建议的副本(长线程),我相信它会进一步澄清。不确定我是否应该检查“这解决了我的问题”按钮?
猜你喜欢
  • 2020-10-31
  • 2020-11-18
  • 2021-02-06
  • 2018-01-30
  • 1970-01-01
  • 1970-01-01
  • 2014-09-28
  • 2017-10-28
相关资源
最近更新 更多