异步的NodeJS混乱 [英] Nodejs asynchronous confusion
问题描述
我似乎无法掌握如何维持与异步的NodeJS控制流。所有嵌套使得code很辛苦在我看来,阅读。我是个新手,所以我可能因小失大。
什么是错的只是编码这样的事情...
函数第一个(){
VAR对象= {
aProperty:'东西',
anArray:['HTML','HTML'];
};
第二(目标);
}函数的第二(对象){
对于(VAR I = 0; I< object.anArray.length;我++){
第三个(object.anArray [I]);
};
}第三个功能(HTML){
//解析HTML
}
第一();
大画面的是,任何I / O是非阻塞的,并在你的JavaScript异步执行;所以,如果你做任何数据库查询,从插座(在HTTP服务器如)读取数据,读取或写入文件,磁盘,等等,你的有无的使用异步code。这是必要的,因为事件循环是单线程的,如果I / O是不是不堵塞,你的程序将在执行其暂停。
您的可以的结构中的code等,有筑巢少;例如:
变种FS =要求(FS);
VAR的mysql =要求('some_mysql_library');fs.readFile('/我的/ file.txt的','UTF8',processFile);功能processFile(ERR,数据){
mysql.query(INSERT INTO TBL SET TXT ='+数据+',doneWithSql);
}功能doneWithSql(ERR,结果){
如果(ERR){
的console.log(有您的查询的问题);
}其他{
的console.log(以下简称查询成功。);
}
}
也有流量控制库如异步(我个人的选择),以帮助避免大量的嵌套回调。
您可能感兴趣的此截屏我关于这个问题的创建。
I can't seem to grasp how to maintain async control flow with NodeJs. All of the nesting makes the code very hard to read in my opinion. I'm a novice, so I'm probably missing the big picture.
What is wrong with simply coding something like this...
function first() {
var object = {
aProperty: 'stuff',
anArray: ['html', 'html'];
};
second(object);
}
function second(object) {
for (var i = 0; i < object.anArray.length; i++) {
third(object.anArray[i]);
};
}
function third(html) {
// Parse html
}
first();
The "big picture" is that any I/O is non-blocking and is performed asynchronously in your JavaScript; so if you do any database lookups, read data from a socket (e.g. in an HTTP server), read or write files to the disk, etc., you have to use asynchronous code. This is necessary as the event loop is a single thread, and if I/O wasn't non-blocking, your program would pause while performing it.
You can structure your code such that there is less nesting; for example:
var fs = require('fs');
var mysql = require('some_mysql_library');
fs.readFile('/my/file.txt', 'utf8', processFile);
function processFile(err, data) {
mysql.query("INSERT INTO tbl SET txt = '" + data + "'", doneWithSql);
}
function doneWithSql(err, results) {
if(err) {
console.log("There was a problem with your query");
} else {
console.log("The query was successful.");
}
}
There are also flow control libraries like async (my personal choice) to help avoid lots of nested callbacks.
You may be interested in this screencast I created on the subject.
这篇关于异步的NodeJS混乱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!