1

I'm having a persistent problem when trying to return a value from any of my async functions for my mongoose service.

What's happening is that it doesn't ever want to return the value, just offering an undefined in most cases, leading me to not know what's going on here. I'm pretty new to this sort of thing so someone who can lend a hand would be a god send.

If I log the value in the getBalance function, it works perfectly fine and the balance is shown as expected.

    async getBalance(username) {
        await users.find({username: username}, function(err, res) {
            return(res[0].balance);
        });
    }

The code below is how I use the function, I await the result (which is always undefined).

    async removeCoins(username, amount) {
        var coins = await parseInt(this.getBalance(username));
        coins -= amount;

        await users.updateOne({ username: username }, { balance: coins }, function(err, result) {
            if (err) { console.log(err); return false; } 
            return true;
        });
    }

As a result I get the following error: CastError: Cast to Number failed for value "NaN" at path "balance"

Any help on this to try and help why I'm not getting a returned value at all would be much appreciated. As explained before If I log the balance inside the get balance function it gets the function perfectly fine.

1 Answer 1

2

That's because await awaits promises' resolutions, not callbacks. Use sth like this:

async getBalance(username) {
  return new Promise((resolve, reject) => {
    users.find({username: username}, (err, res) => {
      if (err) return reject(err);
      resolve(res);
    });
  });
}
async removeCoins(username, amount) {
  // parseInt the result, not the waiting promise
  let coins = parseInt(await this.getBalance(username));

  return new Promise((resolve, reject) => {
    users.updateOne({ username: username }, { balance: coins }, (err, result) => {
      if (err) return reject(err); // or console.warn it
      resolve(result);
    }
  });

}

Then somewhere you call removeCoins:

removeCoins(username, amount)
  .then(() => { ... })  // callback after coins removed
  .catch(err => console.warn(err));

// or simply await the function and catch possible errors later
await removeCoins(username, amount); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.