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
  • 25,319
  • 32
  • 97
  • 163

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
  • 572,313
  • 128
  • 898
  • 1,281
Estus Flask
  • 179,509
  • 61
  • 360
  • 499
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,519
  • 1
  • 12
  • 24