1

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!

sal
  • 11
  • 2
  • You cant use the result of asynchronous function outside of it in synchronous way. – Nikita Mazur Sep 17 '21 at 12:49
  • then is there a way to set this up so I can access the data returned from my request in another function ? – sal Sep 17 '21 at 12:51
  • yes, you can call your function inside the async function – Nikita Mazur Sep 17 '21 at 12:53
  • call which function? – sal Sep 17 '21 at 12:54
  • Duplicate: [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) –  Sep 17 '21 at 13:49
  • as I mentioned in my post, Chris, I understand there are plenty of previous questions about this, but I wanted an answer catered to my code. – sal Sep 17 '21 at 15:18

2 Answers2

0

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
}
Jayendra Sharan
  • 1,043
  • 6
  • 10
  • 1
    Just from a technical standpoint, `async`/`await` code *is* using promises, just `await` instead of `.then`. – crashmstr Sep 17 '21 at 12:58
  • Yes, you are correct. My intention was to highlight the syntactical difference between `async/await` and `.then`. Thanks for pointing out though. I'll update my answer :) – Jayendra Sharan Sep 17 '21 at 13:19
0

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:

  1. We declare a constant apiUrl
  2. We declare an async function getJson
  3. We declare an ordinary function processData
  4. We declare another async function main
  5. We not at long last call our main function, which calls getJson, 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 function

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

Nikita Mazur
  • 1,602
  • 1
  • 5
  • 14