Chapter 1 Ticket: Projection JS | Should `await` return value?

I’m not sure should I await the return value like this

  static async getMoviesByCountry(countries) {
    let cursor
    try {
      cursor = await movies.find(
        { countries: { $in: countries } },
        { projection: { title: 1 } },
      )
    } catch (e) {
      console.error(`Unable to issue find command, ${e}`)
      return []
    }

    return await cursor.toArray()
  }

Because of JS’s async nature, without await on cursor function returns pending promise. And I don’t why but the front end can’t respond that nicely.

And I also guessed toArray of cursor could also be a promise so the second await would be OK.

I couldn’t find the edit button anywhere.
FindCursor | mongodb toArray returns promise must use await

Hi @Umut_Gercek, welcome to the community.
That’s a really good question, thanks for reaching out.

Yes, that’s correct.

But please keep in mind, that all async functions return Promise by default, as per MDN web docs by Mozilla:

Async functions always return a promise. If the return value of an async function is not explicitly a promise, it will be implicitly wrapped in a promise.

Therefore, no matter if you place await or not in front of cursor.toArray(), the caller of this function will always have to wait for the promise to resolve/reject.

For e.g.:
If you want to call this getMoviesByCountry function from one of your other functions, you will need to write the code in the following manner:

async function someOtherFunction() {
  const countries = ["India"]
  const results = await getMoviesByCountry(countries)
  // Notice this->^^^^^
  return results
}

Now, it doesn’t matter whether you have put await before returning the toArray promise or not, you will always put await before assigning the response to the results variable.

Having said that, the only difference between both the approaches is where will the toArray error gets handled(in case if some issue occurs while performing it).
To learn more about the error handling context, checkout the discussion here on Stack Overflow.

In case you have any doubts, please feel free to reach out to us.

Thanks and Regards.
Sourabh Bagrecha,
Curriculum Services Engineer

2 Likes

Thanks for the clarification, I forgot async functions don’t return a pending promise. But I didn’t know it’s useful for choosing the error handling scope.

1 Like