I'm trying to access the data returned inside my POST request, outside of the request, preferably made available globally so I can access it in other functions. What I'm really trying to do is access specific JSON data and make changes to it via other functions and PUT/GET requests (I'm making a command line guessing game.)
NOTE: I've seen a lot of this same question on here but I can't figure out how any answer pertains to my code/none of the answers are really what i'm looking for. I would like to know what step I'm missing in my own code to help me accomplish this.
Here is my code so far. I know I'm close but I'm stuck at this point.
const apiUrl = 'https://word-guessing-game.onrender.com'
let jsondata = "";
async function getJson(url) {
let response = await fetch(apiUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
});
let data = await response.json()
let gameId = data.game.id
return gameId
}
async function main() {
getJson(apiUrl)
.then(data => console.log(data));
}
main();
Right now I have this setup to just return the game.id, because that's what i'm trying to access with a separate function/get request. Any help is appreciated!
This is the way you can use your async data by another function
const apiUrl = 'https://word-guessing-game.onrender.com'
async function getJson(url) {
let response = await fetch(apiUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
});
let data = await response.json()
let gameId = data.game.id
return gameId
}
function processData(data) {
console.log(data)
}
async function main() {
const data = await getJson(url)
processData(data)
}
main().then();
So as you probably know, the javascript is executed from up to down, so lets see whats happening there:
apiUrlgetJsonprocessDatamaingetJson, where we pass our apiUrl as a param. the await key allows us to "wait" for the result from the function so we can access it with our processData functionPS. .then() I used because usually most IDE and inspecting tools are not happy when you call a function which returns a Promise, which you ignore.
If you are using async/await, why not use it like this:
let jsonData = await getJson(apiUrl)
// jsonData will receive the value which getJson is returning
// in this case, the game id.
If you must use .then syntax, you will have to pass a callback to update the value of jsonData
// in getJson function pass another callback
async function getJson(url, cb) {
.
.
.
let data = await response.json()
let gameId = data.game.id
cb(gameId);
And your cb function can look like this
function cb(data) {
jsonData = data; // same json data declared at the top
}