Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I have to put async keyword to functions which have await keywords?

I just want to wait for a process to finish, not want to make the function asynchronous.
See the below code.
I had to make getUserList asynchronous because there was an await keyword in the function. Therefore I also had to write like "await UsersService.getUserList" to execute the method and also I had to make the parent function asynchronous. That's not what I want to do.

import xr from 'xr' //a package for http requests

class UsersService {

  static async getUserList() {
    const res = await xr.get('http://localhost/api/users')
    return res.data
  }

}

export default UsersService

import UsersService from './UsersService'

class SomeClass {

  async someFunction() { //async again!!
    const users = await UsersService.getUserList() //await again!!
  }

}
like image 560
Nigiri Avatar asked Jul 12 '16 05:07

Nigiri


1 Answers

Is it a design choice?

Well this is because of the synchronous nature of JavaScript. If you wanted a function to run an asynchronous command synchronously, it would block up the entire program and this is highly undesirable, bad if it's client side, horrible if it's server-side. For this reason async functions exist. These functions are taken out of the normal flow which is why await works.

Why?

The other reason is that await+async are syntax sugar for promises. Promises are asynchronous and you can't stop that. What this means is that await doesn't make an async function sync, it just holds up the rest of the await function until it finishes. If it did block up the entire event loop, imagine if you wanted to create a app that would send data between clients. Your entire server app would hang everytime it made an async request rather than just make that single request asynchronous.

So think of it this way:

You are not making an async function sync, rather you are making the rest of the program async to cope with it.

So rather than think of async a requirement for await, think of them as a combination (async+await) as that's how they fundamentally work. If you'd like to learn more about async and await I highly recommend taking a read of my blog article which goes in depth on this.

like image 105
Downgoat Avatar answered Sep 23 '22 11:09

Downgoat