以阻塞程序语言的方式进行异步? [英] Do async in a blocking program language way?
问题描述
- 同步方式
例如,红宝石:
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?
例如语言X:
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:
这篇关于以阻塞程序语言的方式进行异步?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!