When To Use Async/Await


#1

Hello guys

Just starting out with JS in general.
I don’t understand when/why I would use async for the controller action so I can use await for the I/O operations. I’ve tested using Async/Await and the behavior was the same as not using it.

This is what I have in the routes file :

Route.get('task','TaskController.index')

This is my controller :

index({response}){

        //i would expect this to be a promise
        //but this actually works
        const newTask = Task.create({
            title : "Some New Task",
            description: "Some New Description Text"
        })

        //same here
        const allTasks = Task.all()
       
        return allTasks
    }

#2

await waits for Promise to be resolved.


#3

It seems it waits for the promise to be resolved without using Await, this is what I’m confused about.


#4

does anybody know?


#5

It works because the promises may have resolved by the time you return which then is send to the client.

Try this and check console to get a better picture:

index ({ response }) {
  const newTask = Task.create({
    title: 'Some New Task',
    description: 'Some New Description Text'
  })
  console.log(newTask)

  const allTasks = Task.all()
  console.log(allTasks)
}

Your console should display:

Promise { <pending> }
Promise { <pending> }

What happens if your object has an error, how will you know/handle it? Or, say you wanted to perform some logic before sending a response. You’re unable to act on these objects since the promises aren’t resolved, and you’ll have to manually resolve the promises, like so:

index ({ response }) {
  const newTask = Task.create({
    title: 'Some New Task',
    description: 'Some New Description Text'
  })
    .then(task => {
      console.log(task)
    })
    .error(e => {
      console.log(e)
    })

  const allTasks = Task.all()
    .then(tasks => {
      console.log(tasks)
    })
    .error(e => {
      console.log(e)
    })

  console.log(allTasks)
}

As described here:

… and then stores the result in the given variable.

Instead of manually resolving promises async/await makes this simple.

async index ({ response }) {
  const newTask = await Task.create({
    title: 'Some New Task',
    description: 'Some New Description Text'
  })
  console.log(newTask)

  const allTasks = await Task.all()
  console.log(allTasks)
}

This is much cleaner in my opinion.

Hope this helps :smiley: