返回带有promise的递归函数

时间:2016-12-23 19:58:01

标签: node.js promise

我正在尝试使用一个功能来浏览端点以获取所有联系人。现在,我的承诺只返回我不明白的2号。我希望它能够返回所有联系人。这是我目前的代码。我希望有人能帮助我理解如何正确地返回联系人数组。

function getContacts(vid,key){

    return axios.get('https://api.hubapi.com/contacts/v1/lists/all/contacts/all?hapikey=' + key + '&vidOffset=' + vid)
    .then(response =>{
    //console.log(response.data['has-more'])
    //console.log(response.data['vid-offset'])
    if (response.data['has-more']){
      contacts.push(getContacts(response.data['vid-offset'],key))
      if(vid === 0){
        return contacts.push(response.data.contacts)
      }else{
        return response.data.contacts   
      }

    }else{
        //console.log(contacts)
        return response.data.contacts
    }
  })


}

2 个答案:

答案 0 :(得分:7)

这是我想出的结果。

function getContacts(vid,key){
    var contacts = []
    return new Promise(function(resolve,reject){

        toCall(0)
        //need this extra fn due to recursion
        function toCall(vid){

                axios.get('https://api.hubapi.com/contacts/v1/lists/all/contacts/all?hapikey=########-####-####-####-############&vidOffset='+vid)
                .then(response =>{
                contacts = contacts.concat(response.data.contacts)
                if (response.data['has-more']){
                  toCall(response.data['vid-offset'])      
                }else{      
                    resolve(contacts)
                }
              })

        }

    })


  }

答案 1 :(得分:6)

我会让getContacts函数返回一个解析为所有联系人列表的promise。在该功能中,您可以链接加载数据页面的各个承诺:

function getContacts(key){
    const url = 'https://api.hubapi.com/contacts/v1/lists/all/contacts/all'

    let contacts = []; // this array will contain all contacts

    const getContactsPage = offset => axios.get(
        url + '?hapikey=' + key + '&vidOffset=' + offset
    ).then(response => {
        // add the contacts of this response to the array
        contacts = contacts.concat(response.data.contacts);
        if (response.data['has-more']) {
            return getContactsPage(response.data['vid-offset']);
        } else {
            // this was the last page, return the collected contacts
            return contacts;
        }
    });

    // start by loading the first page
    return getContactsPage(0);
}

现在你可以使用这样的功能:

getContacts(myKey).then(contacts => {
    // do something with the contacts...
    console.log(contacts);
})