简体   繁体   English

当调用者不期望响应时使用`await`

[英]Using `await` when caller does not expect a response

I have a very simple express app which stores information it receives from clients into a database without hardly any processing.我有一个非常简单的快速应用程序,它将从客户端接收到的信息存储到数据库中,几乎没有任何处理。 Some simplified code to illustrate this:一些简化的代码来说明这一点:

app.post(ANALYTICS_ENDPOINT, async (req, res) => {
  try {
    await insertToDB(req.body)
    res.status(204).send();
  } catch (err) {
    logger.error(err);
    res.status(500).send();
  }
});

This application is deployed to google cloud run and handles a high volume of requests per second.此应用程序部署到谷歌云运行并每秒处理大量请求。 What we have noticed is that removing the await keyword from the route allows each container to handle more requests, at the downside of not capturing errors - so clients will always receive a 204 .我们注意到,从路由中删除await关键字允许每个容器处理更多请求,但缺点是无法捕获错误 - 因此客户端将始终收到204

The other use of await in this would be in insertToDB function which again simplified looks like this:在此使用 await 的另一个用途是在insertToDB function 中,它再次简化如下:

const insertToDB = async (row) => {
  await dbClient.insert(row);
}

As you can see here we are also using await since this action returns a Promise.正如您在此处看到的,我们也在使用await ,因为此操作返回 Promise。

So the question is, should we be awaiting when the caller does not expect a response?所以问题是,当调用者不期望响应时,我们是否应该等待? And can it be the case that avoiding these awaits we can handle more throughput on our app?是否可以避免这些等待,我们可以在我们的应用程序上处理更多的吞吐量?

EDIT: There is a similar question here .编辑: 这里有一个类似的问题。 Yet I think this is different as I am mostly interested in understanding why removing the await allows me to handle 2/3x the number of requests per second.然而我认为这是不同的,因为我最感兴趣的是理解为什么删除await允许我每秒处理 2/3 倍的请求数。

You should wait because your db call is async , so you must wait the insertion to be made before return to the client.您应该等待,因为您的 db 调用是async ,因此您必须等待插入完成,然后再返回客户端。

You can simply use promise resolution to be more concise and clear:您可以简单地使用 promise 分辨率来更简洁明了:

app.post(ANALYTICS_ENDPOINT, async (req, res) => {
    insertToDB(req.body)
    .then(() => res.status(204).send())
    .catch(() => res.status(500).send());
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM