I'm trying to get my Mailchimp interests by querying the API via an Audience ID; I have created the code below which retrieves everything correctly, however when I display the retrieved data outside the forEach
loop, I'm not getting anything stored.
let obj = {};
let arrays = [];
let newdata;
let textlist;
try {
const data = await mailchimp.lists.getListInterestCategories(MailChimpAudienceId);
//console.log(data);
const categories = data.categories;
if (!categories.length) {
console.log(`No categories found in Mail chimp list ${MailChimpAudienceId}`);
}
categories.forEach(async element => {
//console.log(element.id);
obj[element.title] = element.id;
arrays.push(element.id);
newdata = await mailchimp.lists.listInterestCategoryInterests(
MailChimpAudienceId,
element.id,
);
const interests = newdata.interests;
interests.forEach(async element => {
//console.log(element.id, element.name);
obj[element.name] = element.id;
arrays.push(element.id);
textlist += "," + element.id;
});
// console.log(interests);
console.log("obj0>>", obj);
console.log("arr0>>", arrays);
console.log("txt0>>", textlist);
});
console.log("obj1>>", obj);
console.log("arr1>>", arrays);
console.log("txt1>>", textlist);
} catch (e) {
console.log("err>> ", e);
}
console.log("obj2>>", obj);
console.log("arr2>>", arrays);
console.log("txt2>>", textlist);
Output:
obj1>> { MickeyMouse: '21c3bbb614', Music: 'ac86c9d94b' }
arr1>> [ '21c3bbb614', 'ac86c9d94b' ]
txt1>> undefined
obj2>> { MickeyMouse: '21c3bbb614', Music: 'ac86c9d94b' }
arr2>> [ '21c3bbb614', 'ac86c9d94b' ]
txt2>> undefined
obj0>> {
MickeyMouse: '21c3bbb614',
Music: 'ac86c9d94b',
Guitar: '9e05119885',
Drums: 'ca5b24595d',
Bass: '0ce6ed21da'
}
arr0>> [
'21c3bbb614',
'ac86c9d94b',
'9e05119885',
'ca5b24595d',
'0ce6ed21da'
]
txt0>> undefined,9e05119885,ca5b24595d,0ce6ed21da
obj0>> {
MickeyMouse: '21c3bbb614',
Music: 'ac86c9d94b',
Guitar: '9e05119885',
Drums: 'ca5b24595d',
Bass: '0ce6ed21da',
'Big Ears': '5154e49101',
News: 'e49c281f9f',
Fundraising: 'aad8e5ba96'
}
arr0>> [
'21c3bbb614',
'ac86c9d94b',
'9e05119885',
'ca5b24595d',
'0ce6ed21da',
'5154e49101',
'e49c281f9f',
'aad8e5ba96'
]
txt0>> undefined,9e05119885,ca5b24595d,0ce6ed21da,5154e49101,e49c281f9f,aad8e5ba96
How can I store these values so that either the array, the object or the text will have the values outside the secondary loop?
Looks like my issue was with the async aspect of this, as shown in this answer: Resolve await when message arrives
For those playing along at home, the answer was to add a timeout similar to this:
setTimeout(_ => {
// If we have categories, then display them here
console.log(
`Audience ID ${MailChimpAudienceId} has the interests: ${arrays}`,
);
}, 1000); // display after a delay