为什么必须将async关键字添加到具有await关键字的函数中? [英] Why do I have to put async keyword to functions which have await keywords?

查看:77
本文介绍了为什么必须将async关键字添加到具有await关键字的函数中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想等待进程完成,而不想使函数异步.
请参见下面的代码.
我必须使getUserList异步,因为该函数中有一个await关键字.因此,我还必须编写类似"await UsersUserService.getUserList"的代码来执行该方法,并且还必须使父函数异步.那不是我想要的.

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

}

推荐答案

这是设计选择吗?

好吧,这是因为JavaScript具有同步特性.如果您希望某个函数同步运行异步命令,那么它将阻塞整个程序,这是非常不希望的,如果是客户端则很糟糕,如果是服务器端则很糟糕.因此,存在 async 函数.这些功能被排除在正常流程之外,这就是 await 起作用的原因.

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.

另一个原因是, await + async 语法糖,用于承诺.承诺是异步的,您无法阻止.这意味着 await不会使异步函数同步,它只是保留其余的await函数,直到完成为止.如果确实阻塞了整个事件循环,请想象您是否想创建一个在客户端之间发送数据的应用程序.整个服务器应用程序在每次发出异步请求时都会挂起,而不仅仅是使单个请求异步.

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.

您不是要使异步函数同步,而是要使程序的其余部分异步以应对它.

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

因此,与其将 async 视为 await 的要求,不如将它们视为一种组合( async + await ),因为这就是它们的基本工作方式.如果您想了解有关异步的更多信息并等待,我强烈建议您阅读我的

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.

这篇关于为什么必须将async关键字添加到具有await关键字的函数中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆