I am using Axios to perform a GET request against Facebook Graph to get the list of Facebook Pages the user manages. Once I have that, then I am using a for loop to perform another GET request against Facebook Graph to pull data on each Facebook Page that the user manages. I am doing this inside of an async function with a Promise at the end to join all the data together into a single const fbProfile.
My issue is: I cannot get the results from the Axios call in const pages to populate pages array.
My code is below:
async function getfbProfile(token) {
try {
const user = await axios.get('https://graph.facebook.com/me', {
params: {
access_token: `${token}`,
fields: 'picture,accounts',
},
});
const pages = await user.data.accounts.data.forEach((err, pageInfo) => {
axios.get(`https://graph.facebook.com/${user.data.accounts.data[pageInfo].id}`, {
params: {
access_token: `${token}`,
fields: 'picture,name',
},
});
});
const fbProfile = await Promise.all([user, pages]);
debug(fbProfile);
} catch (err) {
debug(err.stack);
}
}
I know that the first call goes through and the for loop calls go through. I verified the for call loop works by modifying const pages to look like below and seeing both calls successfully go to Facebook Graph.
const pages = await user.data.accounts.data.forEach((err, pageInfo) => {
axios.get(`https://graph.facebook.com/${user.data.accounts.data[pageInfo].id}`, {
params: {
access_token: `${token}`,
fields: 'picture,name',
},
})
.then((result) => {
debug(result);
});
});
I would greatly appreciate any help. I've been wracking my brains on this for the last two days. Thank you for any help you can give.
ANSWER
Thanks to Patrick Roberts for his help. Since I am using Airbnb's ESLint profile, I had to modify his example below to pass linting. Thanks again!
async function getfbProfile(token) {
try {
const user = await axios.get('https://graph.facebook.com/me', {
params: {
access_token: token,
fields: 'picture,accounts',
},
});
const pages = Promise.all(user.data.accounts.data.map(({ id }) => axios.get(`https://graph.facebook.com/${id}`, {
params: {
access_token: token,
fields: 'picture,name',
},
})));
const fbProfile = await Promise.all([user, pages]);
debug(fbProfile);
} catch (err) {
debug(err.stack);
}
}
Array.forEach()returnsundefined; you'll want to useArray.map()instead.mapneeds toreturntheaxios.get(...)