Retrieving a value in a function in Node.js

I’m struggling with callbacks in Node.js. I simply want playerNumber to be set to the number of players in my collection of Players. The console.log works, but I can’t get the variable out of the function and into the playerNumber variable.

And if there’s a simpler way get this value for use in the rest of my backend code, I’m all ears. I’m clearly new at Node.js, but the code always seems more involved than I’m expecting.

Thanks in advance!

var playerNumber = function countPlayers(callback){
    Player.count(function(err, numOfDocs) {
        console.log('I have '+numOfDocs+' documents in my collection');
        callback(err, numOfDocs);
    });
}

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

It’s probably async, and it’s a typical first-timer experience to want to “get back to normal” on the call chain on the way back from async call. This can’t be done, but it’s not so bad to live with it. Here’s how…

  • Step 1: Promises are better than callbacks. I’ll leave the long story
    to others.
  • Step 2: Callbacks can be made into promises

In the OP case…

// The promise constructor takes a function that has two functions as params
// one to call on success, and one to call on error.  Instead of a callback
// call the 'resolve' param with the data and the 'reject' param with any error
// mark the function 'async' so callers know it can be 'await'-ed
const playerNumber = async function countPlayers() {
  return new Promise((resolve, reject) => {
    Player.count(function(err, numOfDocs) {
      err ? reject(err) : resolve(numOfDocs);
    });
  });  
}
  • Step 3: Yes, the callers must deal with this, and the callers of the callers, and so on. It’s not so bad.

In the OP case (in the most modern syntax)…

// this has to be async because it 'awaits' the first function
// think of await as stopping serial execution until the async function finishes
// (it's not that at all, but that's an okay starting simplification)
async function printPlayerCount() {
  const count = await playerNumber();
  console.log(count);
}

// as long as we're calling something async (something that must be awaited)
// we mark the function as async
async function printPlayerCountAndPrintSomethingElse() {
  await printPlayerCount();
  console.log('do something else');
}
  • Step 4: Enjoy it, and do some further study. It’s actually great that we can do such a complex thing so simply. Here’s good reading to start with: MDN on Promises.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x