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.
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: