How to call the Async and Await in firestore

kn3l

I have a function for get the data from firestore db.

PlayerService.js

 //...
 async getHighestPlayers(game){
    const snapshot = await this.db
    .collection(game)
    .orderBy("score","asc")
    .limitToLast(1)
    .get();

    // What should I need to return ?

    snapshot.forEach((doc) => {
        console.log(doc.id, '=>', doc.data());
      });
  }  

index.js

router.get('/', function(req, res, next) {
  const  highestPlayers = playerService.getHighestPlayers("game1"); 
  res.render('index', { highestPlayers: highestPlayers});
});

How to make async getHighestPlayers(game) return , so I can call and use to display it result?

Doug Stevenson

You haven't really said what exactly the template needs to render. The template will receive whatever you send. If you're working with some spec to fulfill, you should covert the snapshot to whatever the client expects. We don't have that information.

In the absence of a specification, you could simply send the entire contents of the matching document (if one was even found):

async getHighestPlayers(game) {
  const snapshot = this.db
    .collection(game)
    .orderBy("score","asc")
    .limitToLast(1)
    .get();

  if (snapshot.docs.length > 0) {
    return snapshot.docs[0].data();
  }
  else {
    return undefined;
  }
}  

Then you will have to write some code to determine if there was actually a document present, and decide what you want to send if there was not:

router.get('/', function(req, res, next) {
  const highestPlayers = playerService.getHighestPlayers("game1"); 
  if (highestPlayers) {
    res.render('index', { highestPlayers: highestPlayers});
  }
  else {
    // what do you want to do if the document was missing?
  }
});

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related