简体   繁体   English

异步如何在 Express 中工作?

[英]How does async work in Express?

I found the following on the ExpressJS guide :我在ExpressJS 指南中发现了以下内容:

var mysql      = require('mysql');
var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'dbuser',
  password : 's3kreee7'
});

connection.connect();

connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {
  if (err) throw err;
  console.log('The solution is: ', rows[0].solution);
});

connection.end();

Isn't this supposed to be bad practice?这不应该是不好的做法吗? The way I see it, it is possible for the connection to end before the query can be executed.在我看来,连接有可能在执行查询之前结束。 Wouldn't that give an error?那不会报错吗?

As stated here :如前所述这里

  • Every method you invoke on a connection is queued and executed in sequence.您在连接上调用的每个方法都会排队并按顺序执行。

  • Closing the connection is done using end() which makes sure all remaining queries are executed before sending a quit packet to the mysql server.关闭连接是使用 end() 完成的,它确保在向 mysql 服务器发送退出数据包之前执行所有剩余的查询。

So even though the call to the end() method can be made before the query has completed, it won't actually be executed until the query has finished executing.因此,即使可以在查询完成之前调用end()方法,它也不会在查询完成执行之前实际执行。

This has to do more with the mysql package than NodeJS itself.这与mysql包比 NodeJS 本身有更多关系。

Your question How does async work in Express?您的问题async 在 Express 中是如何工作的? and Isn't this supposed to be bad practice?这不应该是不好的做法吗? can be answered in many ways, but for clarity I would like to explain that It depends !!!!可以通过多种方式回答,但为了清楚起见,我想解释一下这取决于!!!!

It generally is very bad practice, assuming you don't know the actual implementation.假设您不知道实际实现,这通常是非常糟糕的做法。

If the the implementation is really simple, where it does exactly what you ask -- ie closes or ends the connection when end is executed then it could lead to rather ugly race conditions where it may or may not work depending on the load of the machines.如果实现真的很简单,它完全按照您的要求执行 - 即在执行end时关闭或结束连接,那么它可能会导致相当丑陋的竞争条件,根据机器的负载它可能会或可能不会工作.

However, a clever implementation that does reference counting -- that is the end does not actually close the connection but just sets a flag to say -- " when last callback is done then close " -- then it may work.然而,一个进行引用计数的聪明实现——即end实际上并没有关闭连接,而只是设置一个标志来说明——“当最后一个回调完成后关闭”——那么它可能会起作用。

If the mysql connector it implemented using reference counting then this may well work fine -- but that is not the same as saying that it is good practice for everything you find as a plugin.如果它使用引用计数来实现 mysql 连接器,那么这可能会很好地工作 - 但这并不等于说它是作为插件找到的所有东西的好习惯。

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

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