0

I have this code example:

function getGameState() {
    return(fetch("http://localhost:8080/game_state"))
        .then(resp => resp.json())
        .then(data => {
            return data;
        });
};

I'm calling it from another function, like so:

function Game() {
    const gmState = getGameState()
    console.log(gmState);
}

The console output is as follows:

Promise {<pending>}

When I open up the arrow icon in the console, I see this:

Promise {<pending>}
[[Prototype]]: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: Object
available: null
board: Array(1)
0: {player: 1, x: 1, y: 0}
length: 1
[[Prototype]]: Array(0)
player_turn: 2
[[Prototype]]: Object

I need to pull the data from player_turn and board so I can pass those pieces to other functions.

The only examples I've found show console.log in the last .then, which I'm able to accomplish. I tried using async and await and many variations on this. I'm not able to find any working examples, and I'm starting to wonder if this sort of pattern is possible in React.

1 Answer 1

1

Use async/await to fulfill the promises

async function Game() {
  const gmState = await getGameState()
  console.log(gmState);
}
Sign up to request clarification or add additional context in comments.

3 Comments

I'm seeing this, but this, once again, doesn't allow me to do anything but console.log. That's the issue I'm having. I can't do anything with it besides log. I want to pull the data out of it and do something with it. It is possible to organize code like this?
what do you want to do?
I want to assign the result to a variable in the other function. the result has data I need to pass to another function to use in it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.