I wonder if anyone can help me with this JS async/await question. I am learning more about these concepts but don't fully understand how to use them yet.
I want to use get_JSONfromInstaAPI()
as a generic method to get responses from an API, and return the expected JSON, but when I utilise it in setup_instragramFeed()
, it seems it does not await long enough. I think this may be because the first function has multiple asynchronous steps, and resolves when the first step has completed, but I'm not sure. How do I properly await the return from this function?
Thanks in advance!
async function get_JSONfromInstaAPI(uri) {
fetch(uri)
.then(response => response.blob())
.then(blob => {
// console.log(blob);
blob.text()
.then(value => {
self.objectName = JSON.parse(value);
// console.log(self.objectName);
const json = self.objectName;
console.log(json); // returns the expected json, AFTER the console log in the other function
return json;
})
.catch(error => {
// console.log("Error is" + error);
});
})
.catch(error => {
// console.log("Error is" + error);
});
}
async function setup_instragramFeed() {
const access_token = 'XXX';
const uri_base = 'https://graph.instagram.com/';
const media_uri = uri_base+'/me/media?fields=id,media_type,caption,media_url&access_token='+access_token;
const media_json = await get_JSONfromInstaAPI(media_uri);
console.log(media_json); // returns undefined, BEFORE the console log in the other function
}