Lesson awaits vs DAO awaits

Hi,
My question / confusion concerns how await is used differently (as far I can see) in the videos and lesson code, versus how it’s used the DAO code.

For example, lessons/cursor-methods-agg-equivalents.spec.js has

const sortedCursor = movies
  .find({ directors: "Sam Raimi" }, { _id: 0, year: 1, title: 1, cast: 1 })
  .sort([["year", 1]])

const movieArray = await sortedCursor.toArray()

with no await before movies. Whereas in moviesDAO.js, getMovies() has

try {
  cursor = await movies
    .find(query)
    .project(project)
    .sort(sort)
} catch (e) {
  console.error(`Unable to issue find command, ${e}`)
  return { moviesList: [], totalNumMovies: 0 }
}
//...
try {
  const moviesList = await displayCursor.toArray()

Both use await before cursor.toArray(), but they appear inconsistent with await preceeding movies.

Could someone explain?

Hi @Dave_91902

Firstly, apologies for the apparent inconsistencies. You can use await in both of these styles. The MongoDB NodeJS Driver will always return a promise automatically unless a callback has been passed to it, await and async are based completely on top of promises. In the example with getMovies you would call it using await which would then be similar to cursor-methods-agg-equivalents.spec.js where you set the variable movieArray to the await’ed sortedCursor.toArray() function result.

More simply put, moviesDAO.js getMovies() uses a nested set of awaits so that the various asynchrous function results are bubbled back up to the final returned value for getMovies().

Let me know if that helps clarify this and I want to share the 80/20 Guide to Async/Await which I found (and indeed still find useful) in understanding the await/async aspects in NodeJS.

Hope this helps!
Eoin

1 Like

Thanks very much Eoin, I will have a read!