我断断续续地使用 node.js 已经大约 6 个月了。但是,我想我仍然不完全理解围绕异步调用设计程序。
以我最近的程序为例,它需要读取配置,使用该配置连接到数据库,然后异步连接到数据库中的每个地址。
我正在使用模块 fnoc和 node-mysql ,但这只是伪代码。
// first, get the config
fnoc(function(err, confs){
// code stuff in here
//now check that there's a database config
if (confs.hasOwnProperty("database"))
{
// set up db connection
var mysql_conn = mysql.createConnection({
host: confs.database.host,
user: confs.database.user,
password: confs.database.password,
database: confs.database.database
});
// do some querying here.
mysql_conn.query(query, function(err, records, fields){
records.forEach(function(host){
// four levels in, and just now starting the device connections
});
});
}
});
每次我写这样的东西时,我都觉得自己做错了什么。我知道 promises 和异步 Node 库,但似乎如果这些是解决方案,它们应该是默认功能。是我做错了什么,还是只是没有为我点击?
编辑:一些建议包括使用回调函数,但不知何故这似乎更糟(除非我做错了,这是完全可能的)。您最终会在另一个函数中调用一个函数,这看起来特别像意大利面条。
上面的例子,有函数:
function make_connection (hosts) {
hosts.foreach(function(host){
//here's where the fun starts
};
}
function query_db(dbinfo){
var mysql_conn = mysql.createConnection({
host: dbinfo.host,
user: dbinfo.user,
password: dbinfo.password,
database: dbinfo.database
});
// do some querying here.
mysql_conn.query(query, function(err, records, fields){
make_connection(records);
});
}
// first, get the config
fnoc(function(err, confs){
// code stuff in here
//now check that there's a database config
if (confs.hasOwnProperty("database"))
{
// set up db connection
query_db(confs.database);
var mysql_conn = mysql.createConnection({
host: confs.database.host,
user: confs.database.user,
password: confs.database.password,
database: confs.database.database
});
// do some querying here.
mysql_conn.query(query, function(err, records, fields){
records.forEach(function(host){
// four levels in, and just now starting the device connections
});
});
}
});
最佳答案
异步函数和回调的目的是避免对象之间的任何冲突(发生的次数可能比您想象的要多!)。
我想向您介绍这位异步爱好者:http://www.sebastianseilund.com/nodejs-async-in-practice
是的,回调确实需要一些时间来适应,但这是值得的!
关于javascript - 我想我不会 "get"异步编程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20669123/