我试图有一个功能,将通过端点页面来获取所有的联系人.现在我的承诺只返回我不明白的数字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
}
})
}
Run Code Online (Sandbox Code Playgroud)
我会让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);
}
Run Code Online (Sandbox Code Playgroud)
现在你可以使用这样的函数:
getContacts(myKey).then(contacts => {
// do something with the contacts...
console.log(contacts);
})
Run Code Online (Sandbox Code Playgroud)
这是我想出的结果.
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)
}
})
}
})
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4644 次 |
| 最近记录: |