Returning a recursive function with a promise
I would make the getContacts
function return a promise that resolves to a list of all contacts. Within that function you can chain the individual promises that load a page of your data:
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);
}
Now you can use the function like this:
getContacts(myKey).then(contacts => {
// do something with the contacts...
console.log(contacts);
})
Here is the result I came up with.
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)
}
})
}
})
}