I have an apollo-server setup in my backed, I want to use a post request API inside one of my resolvers and then use the response from that API to return it to my client. but the problem am having is the return statement is running before the API response get returned. there is my code sample bellow.
module.exports = {
Mutation: {
checkFace: async () => {
console.log("Checking.....");
let confidence;
var parameters = {
image_url1: "link to image 1",
image_url2: "link to image 2",
};
facepp.post("/compare", parameters, function (err, res) {
if (!err) {
confidence = res.confidence;
} else {
console.log(err);
}
});
return confidence
},
},
};
That's because the faceapp.post is probably running asynchronously. Your checkFace function is correctly used as async that's fine, but inside where you call the POST you should await the response and then return it
confidence = await res.confidence;
Also when using the function make sure you await for it to finish, so call it with
let someResponse = await Mutation.checkFace();
console.log(someResponse);
or
Mutation.checkFace().then(response => {
console.log(response);
});
Whichever you prefer depending on your situation.
https://nodejs.dev/learn/modern-asynchronous-javascript-with-async-and-await