2
async function main() {
  console.log("Start")
  await Author.create({name: 'Some Guy'}, function (err, awesome_instance) {
    console.log("This should be next, but its not")
  });

  console.log("This should be last, but it's not")
}

main()

The final log statement is logging before the second. Why is this the case if I'm using await?

Ben G
  • 26,091
  • 34
  • 103
  • 170

2 Answers2

4

Mongoose methods switch to callback mode when callback is specified, and switch to promise mode when it isn't.

It should be:

async function main() {
  try {
    await Author.create({name: 'Some Guy'});
  } catch (err) {
    console.error(err);
  }
  console.log("This should be next, but its not");
  console.log("This should be last, but it's not");
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Estus Flask
  • 206,104
  • 70
  • 425
  • 565
0

Your await is waiting for Author.create to return/resolve. But the first log statement is in a callback and is called asynchronously by Author.create, so the await does not apply.

If you implement Author.create using promises you can use await.

sliptype
  • 2,804
  • 1
  • 15
  • 26