Skip to content

Synchronously calling async map function

2nd August 2018

My newest finding today was calling an asynchronous function inside map. This is a dumb idea if you don't for-sure/100% know that the array you are mapping doesn't have more less than 10.

I for sure know that the array of ObjectIds I'm trying to call upon has maximum 3 values, and I want to expose only some fields to the client so I needed to map the output.

Let me give you an example:

const topScoringStudents = [
    {name: "Ashish", scorecard: ObjectId("5f926adhj0171bak")},
    {name: "Nikhil", scorecard: ObjectId("5f926adhj0141byk")"},
    {name: "Steve", scorecard: ObjectId("5f926adhj0178bpk")"}
    ];

These are the top 3 students out of all and I have to query their scorecard document which is inside the scorecard collection inside a MongoDB database. I need to make a async fetch call while also mapping the fields that come from that.

There are 2 ways to approach this problem (that's how many I could think of right now):

  • Take all scorecard ObjectIds into an array and query once using the $in operator and then stitch all values inside a new object and send it to the client.
  • Asynchronously map and await for the query to finish and send only required values as output (this option queries 3 times in a database inside)

I chose the 2nd option, to begin with let's just make a async map function:

const mapStudentScorecard = async (e) => {
    const scoreCard = await Scorecard.findOne({_id: e.scorecard}).lean();
    return {
        student_name: e.name,
        score: scoreCard.score,
        ranking: scoreCard.class_ranking
    }

const finalResult = topScoringStudents.map(mapStudentScorecard);
// output: {null, null, null}
}