0

I am trying to write a function that takes a URL and returns the engagement stats from Facebook Graph API against that URL. But I am facing trouble as my function is just giving me Promise { <pending> } as output.

Here is my code:

const getFacebookStats = async (link, ACCESS_TOKEN) => {
  try {
    const resp = await axios.get(
      `https://graph.facebook.com/v12.0/?id=${link}&fields=engagement&access_token=${ACCESS_TOKEN}`
    );
    return resp;
  } catch (err) {
    // Handle Error Here
    console.error(err);
  }
};

Any help would be much appreciated.

Nabeel Hassan
  • 149
  • 1
  • 1
  • 9
  • How are you calling this function ? `getFacebookStats` is an asyncronous function, ans so it will return a promise. Are you awaiting it ? – Gray Hat Nov 04 '21 at 12:00
  • I try something like `const response = await getFacebookStats(link, ACCESS_TOKEN)` then `console.log(response)`, this produces an error `SyntaxError: await is only valid in async functions and the top level bodies of modules` – Nabeel Hassan Nov 04 '21 at 12:12

1 Answers1

0

Call your function like this:

getFacebookStats(link, ACCESS_TOKEN).then(response => {
    console.log(response);
}).catch(error => {
    console.error(error);
});

Or you could call it using await inside an async function.

Check this answer for a more detailed explaination of Promises in javascript.

Gray Hat
  • 368
  • 2
  • 10