Node.js的 混淆了非阻塞的方法

好吧,似乎我很难开始思考..嗯..function的方式..或asynchronous的方式。

我对node.js比较陌生,但是我有很多年的C#,java,c ++经验。

图片我有简单的任务。 这个任务的想法是每一行都应该在上一行完成之后执行(阻塞操作)。 正常的做法,让我说,C#。 此外,(这是这篇文章的原因)让我们想象我们在我们的代码中有一条条件线。 这个伪代码如下:

f = OpenFile("aaa.txt") If f.ReadLine(1) == "bbb" // read the first line line = f.ReadLine(2) // read the second line else line = ReadLine(3) // read the third line DataBase.Insert(line) // store the line in some database, lets say in mysql DeleteFile(f) 

很简单。 现在,据我所知,node.js通过向几乎每个函数添加callback来使用非阻塞方法。 这样,这个简单的任务似乎成了我的噩梦。 如果我尝试重现上面的代码,它将如下所示:

 OpenFile(f, function() { ReadLine(f, 1, function(line) { if line == "bbb" { ReadLine(f,2, function(line) { DataBase.Insert(line, function() { DeleteFile(f); }); }); { else { ReadLine(f,3, function(line) { DataBase.Insert(line, function() { // the same again DeleteFile(f); }); }); } }); }); 

好吧,你看到了这一点。 在这个例子中,如果我需要确保只有在成功打开文件后才能读取该行,则需要在callback中写入“下一行的逻辑”。 我应该继续在“上一行callback”中写下“下一行逻辑”,如果不行,我会遇到这种情况,例如,我会尝试读取文件的行,没有打开我还要指出,在我的实际代码中,我确实使用了非阻塞函数,例如:

 jsdom.env(..) fs.exec(..) 

我的方法在上面的代码中是否正确? 或者我错过了什么,我的方法是完全错误的? 我希望有一个更好的解决scheme和方法。

感谢您的时间。

你的方法似乎是正确的,这是它的工作方式。 你是对的,很难find一个时尚的方式来编写asynchronous代码。

处理这个工具的一个工具是Step ,它允许你定义一系列相互作用的函数:

 Step( function(...) { OpenFile... }, function(...) { ReadLine(f, 2, this); }, function(err, line) { if (err) throw err; if (line === "bbb") DataBase.Insert(line, this); else DataBase.Insert(line, this); }, function(...) { DeleteFile... } ); 

在步骤中, this起到回叫的作用,并由给定序列中的以下function替代。 也可以触发并行任务。 文档很简单。

可能你更喜欢这种方式。


或者没有其他工具:

没有必要使用匿名函数作为callback。 您可以定义一个函数并将其名称作为callback函数,从而可以在不使用其他工具的情况下消除代码重复。 小草案:

 OpenFile(f, function() { ReadLine(f, 1, function(line) { if line == "bbb" { ReadLine(f,2, insertIntoDatabaseAndDeleteFile); { else { ReadLine(f,3, insertIntoDatabaseAndDeleteFile); } }); }); function insertIntoDatabaseAndDeleteFile(line, f) { DataBase.Insert(line, function() { DeleteFile(f); }); } 

作为一名长期的C ++开发人员,我可以告诉你:

a)你的代码没问题b)你的感觉也没问题。 c)时间越来越好。 在此期间,我感到非常不舒服的调用C ++中的同步io函数

下面是你的代码的另一个版本,给你一个印象,你可以在JS中做什么:

 OpenFile(f, function() { var myReadInsDel = function( f, n, callback ) { ReadLine(f,3, function( line ) { DataBase.Insert( line, function() { DeleteFile( f, callback ); }); }); ReadLine(f, 1, function(line) { if line == "bbb" { myReadInsDel( f, 2 ); // you could provide also a callback here } else { myReadInsDel( f, 3 ); // you could provide also a callback here } }); });