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

风流意气都作罢 提交于 2021-02-18 22:30:27

问题


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!!
  }

}

回答1:


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.



来源:https://stackoverflow.com/questions/38320610/why-do-i-have-to-put-async-keyword-to-functions-which-have-await-keywords

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!