用promise来返回一个recursion函数

我想要一个function,将页面通过一个端点来获取所有的联系人。 现在我的诺言只是返回我不明白的数字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 } }) } 

我会让getContacts函数返回一个承诺,parsing为所有联系人列表。 在这个函数中,你可以链接装载数据页面的个体承诺:

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

现在你可以使用这样的function:

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

这是我想出来的结果。

 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=e5ca5aac-d9e0-4d2c-aeed-93179d563c6c&vidOffset='+vid) .then(response =>{ contacts = contacts.concat(response.data.contacts) if (response.data['has-more']){ toCall(response.data['vid-offset']) }else{ resolve(contacts) } }) } }) }