0

Cannot get the async / await functions to work properly in my card game app.

(a) I get the 201 response with no data.

(b) the deck document seems to be created afterwards, with the players field an empty array, indicating it is done after the deck is saved to the mongoDB

Below is my code. Any help is appreciated.

router.js

router.post('/game', (req, res, next) => {
  try {
    const { cards, playerNames, attributes } = req.body;

    const newDeck = deck.start(cards, playerNames, attributes);
    res.status(201).send(newDeck);
  } catch (err) {
    next(err);
  };
});

/services/deck.js

 exports.start = async (cards, playerNames, attributes) => {
  try {
    const users = await user.create(playerNames);

    const deck = new Deck({
      cards,
      attributes,
      players: users
    });

    return await deck.save((err, newDeck) => {
      if (err) console.log(err);
      console.log('RESULT', newDeck);
    });
  } catch (err) {
    console.log(err);
  }
};

/services/user.js

exports.create = async (users) => {
  if (users.constructor === String) {
    const user = new User({displayname: users});

    return await user.save((err, newUser) => {
      if (err) console.log(err);
      console.log('NEW USERS ', user);

      return newUser;
    });
  } else if (users.constructor === Array) {
    let userList = [];

    await users.forEach(name => {
      const user = new User({displayname: name.toString()});

      return user.save((err, newUser) => {
        if (err) {
          console.log(err);
        } else {
          userList.push(newUser);
          return newUser;
        }
      });
    });
    console.log('NEW USERS ', userList);

    return userList;
  };
};
3
  • @AvivLo He is. Async/Await is one way to manage promises. Commented Apr 20, 2020 at 16:34
  • Sorry, I wanted to say callback. Commented Apr 20, 2020 at 16:38
  • Oh, yeah you are right. The save method doesn't appear to return a promise. Commented Apr 20, 2020 at 16:47

1 Answer 1

1

I am not familiar how you're handling promises,

but forEach is not promise-aware, that's how it has been designed, so it will not handle your asynchronous code properly

replace it with normal for loop or for-of loop, and add the await keyword in front of the user.save() method

Sign up to request clarification or add additional context in comments.

Comments

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.