-1

I'm trying to create saving feature for my little game (Javascript, Axios, Express, NodeJS MongoDB). Problem is that I don't really understand axios promises and async/await features or more accurately I don't know how to implement them into my code. I want to get data from my mongodb and use it in variable/method so I can change stats of player etc. later as needed. I have been reading all possible guides and similiar posts, but I have no idea why they don't work for me. Any help would be appreciated!

After messing around and trying everything I found on web, here's currently part of my code:

case "Load":

   function getMySave () {
  return axios.get("http://localhost:3000/save", {
    params: {
        name: username
    }
  })
  .then(response => {
      console.log(response.data)
    return response.data
  })
  .catch(error => {
    console.log(error);
    return Promise.reject(error);
  });
}
const waitIgetMySave = async () => {
    const playerSave = await getMySave();
    return playerSave;
  };

  playerSave = (waitIgetMySave());
  console.log(playerSave)

player = new Player(username, playerSave.class, playerSave.health, playerSave.mana, playerSave.strength, playerSave.agility, playerSave.speed, playerSave.maxhp);

break;
            }

But this code just returns following:

Promise { : "pending" }

Object { _id: "5e9945f238a82e084c7cb316", name: "Jesse", class: "Rogue", ..... }

So object itself is working fine, but I can't apply it to anything outside of the axios.get function. It always gives me pending, promise[Object], undefined or such that I can't use in my player object or variables. I'm quite sure that I'm doing something wrong with async/await features where, but after spending few days trying to solve this problem, I'm really running out of options.

And yes, I looked at [How do I return the response from an asynchronous call?

[1]: How do I return the response from an asynchronous call? but that seems to be for Ajax and I just fail to understand and implement those in my own code.

1 Answers1

0

The key principles of async code

  • You cannot make asynchronous code synchronous.
  • Promises are tools to manage asynchronous code in a consistent way
  • The async and await keywords are tools to manage Promises in a way that looks synchronous (but really just does clever stuff with functions going to sleep while they wait and allowing the rest of the program to keep running)

The specific issue with your code

  • waitIgetMySave is defined as async so it returns a Promise
  • When you call it (playerSave = (waitIgetMySave());) you do not await it, so you get the promise and not the resolved value from the promise.

(And waitIgetMySave will have gone to sleep while it waits for getMySave to resolve. This allows the rest of the program to keep going, assign the promise to playerSave and log that promise in the meantime).

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Sorry but I just don't get it. If I try to add await like: playerSave = await (waitIgetMySave()); it just gives me an error that await is not defined. How am I supposed to make this work? Or is there way around this? – bonekuukkeli Apr 20 '20 at 10:58
  • @bonekuukkeli — `await waitIgetMySave()`. – Quentin Apr 20 '20 at 11:02
  • You mean playerSave = await waitIgetMySave() ? Then it gives me following errors: ReferenceError: GameManager is not defined localhost:3000:1:1 SyntaxError: await is only valid in async functions and async generators – bonekuukkeli Apr 20 '20 at 11:11
  • Well yes. See the very first principle. "You cannot make asynchronous code synchronous.". `await` only works inside `async` functions. – Quentin Apr 20 '20 at 11:13
  • Thanks for twisting my brain to correct position! I was looking at wrong place all these days. So problem was my main function, which set up stats for characters and also for this load case! Adding async into main function worked. – bonekuukkeli Apr 20 '20 at 11:19