是否以阻塞程序语言的方式进行异步? [英] Do async in a blocking program language way?
问题描述
- 同步方式
例如,ruby:
con = Mysql.new('localhost')
rs1 = con.query('select * from test01') # A
rs2 = con.query('select * from test02') # B
rs = getResult(rs1, rs2) # C
con.close
因此,A
将阻止执行. B
将一直执行到A
完成. C
so A
will block the execution. B
will be executed until A
is done. So does C
- 异步方式
例如nodejs
var mysql = require('mysql');
var connection = mysql.createConnection({host : 'localhost',});
connection.connect();
connection.query('SELECT * from test01', function(err, rows, fields) {
console.log(rows);
}); // A
connection.query('SELECT * from test02', function(err, rows, fields) {
console.log(rows);
}); // B
connection.end();
A
不会阻止B
,但通常代码应如下所示:
A
will not block B
, but normally the code should look like this:
connection.query('SELECT * from test01', function(err, rows1, fields) { // A
connection.query('SELECT * from test02', function(err, rows2, fields) { // B
getResult(rows1, rows2); // C
});
});
或者使用promise来并行执行
Or Using promise to execute in parallelly
Promise.all([
connection.query('SELECT * from test01'),
connection.query('SELECT * from test02'),])
.then(function(data) {
getResult(data[0], data[1])
})
我的问题是,是否一定要这样?可以通过编写同步代码来获得异步效果吗?
My question is, does it have to be in this way? Is it possible by writing sync code but get a async effect?
例如,languageX:
For example, languageX:
VAR con = Mysql=>new('localhost') # A
VAR rs1 = con=>query('select * from test01') # B
VAR rs2 = con=>query('select * from test02') # C
VAR rs = getResult(rs1, rs2) # D
con=>close # E
过程是:
- A,只需执行它并转发到B
- B,执行它并转发到C,并在内部进行标记,因为这是IO阻塞
- C,执行它并转发到D,并在内部进行标记,因为这是IO阻塞
- D,仅在rs1和rs2准备好时才执行,但此处不阻塞,也不执行E(可以处理其他请求等)
- 当rs1和rs2准备就绪时,执行并转发给E
在这里我要说的是,没有回调的麻烦,但是干净,简单的纯代码,我们可以获得无阻塞的IO.
What am I trying to say here is, without the mess of callback but clean, simply, plain code we can get non-blocking IO.
推荐答案
我的问题是,是否一定要这样?可以通过编写同步代码来获得异步效果吗?
My question is, does it have to be in this way? Is it possible by writing sync code but get a async effect?
是的.您可以在Node 7+上使用async/await,也可以在旧版本的Node上使用基于生成器的协程.
Yes. You can use async/await on Node 7+ or generator based coroutines on older versions of Node.
它看起来像:
var x = await f1();
var y = await f2(x);
// ...
甚至:
var y = await f2(await f1());
// ...
,但仍将是异步且非阻塞的. 您可以将该语法与任何返回诺言的函数一起使用-就像Node中的许多数据库驱动程序和ORM/ODM一样.
but it will still be asynchronous and non-blocking. You can use that syntax with any function that returns a promise - like a lot of the database drivers and ORMs/ODMs in Node do.
有关更多示例,请参见这些答案:
See those answers for more examples:
- How do I send multiple queries from one endpoint with Express?
- I can't get the value of "result" in Node.js
这篇关于是否以阻塞程序语言的方式进行异步?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!