1

I'm writing a simple query to return the first name of a user of my Facebook Messenger chat bot, see below:

async queryFB(id) {
  const fb_page_access_token = dotenv.FACEBOOK_ACCESS_TOKEN
  const response = await get("https://graph.facebook.com/v3.3/"+ id + "?fields=first_name&access_token=" + fb_page_access_token);
  const json = await response.json();

  return json.first_name
}

async fbFirstName() {
  const fbUserID = session.user.id

  try {
    const firstName = await queryFB(fbUserID);
    console.log(firstName);
  } catch(e) {
    console.log("Error: " + err);
  }
}

I was following this post here

The problem is that it only returns [object Promise]. I thought the solve for this was to use async and await but I still have the same problem.

Sean
  • 494
  • 6
  • 23

1 Answers1

1

After a lot of fiddling with the code I managed to solve this as follows:

   function fbFetch() {
      const fb_page_access_token = process.env.FACEBOOK_ACCESS_TOKEN
      var fbID = 716540089

      fetch('https://graph.facebook.com/v3.3/' + fbID + '?fields=first_name&access_token=' + fb_page_access_token)

      .then(function(response) {
        return response.json();
      })
      .then(function(myJson) {
        var fbName = JSON.stringify(myJson.first_name);
        var fbNameTrim = fbName.slice(1,-1);
        console.log(fbNameTrim);
        turnContext.sendActivity("Hi " + fbNameTrim + "! From inside fbFetch() before return fbNameTrim");
        return fbNameTrim;
      })
      catch(e) {
        console.log("Error: " + err);
      }
    }

The changes I made are as follows:

  • I updated the const fb_page_access_token call as it my syntax was wrong in the original post
  • I added .then statements to ensure that each step of the function was completed before moving on to the next to resolve some [object Promise] issues I was having
  • I used stringify to turn the JSON object into a string
  • I have used the slice function to take off the first and last characters of the string that is returned for first_name as they were inverted commas (“first_name”)
Sean
  • 494
  • 6
  • 23