我想我不会“获得”asynchronous编程

现在我一直在使用node.js大约6个月。 但是,我想我还是不完全明白devise一个围绕asynchronous调用的程序。

以我最近的程序为例,它需要读取一个configuration文件,使用该configuration文件连接到数据库,然后asynchronous连接到数据库中的每个地址。

我使用模块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 }); }); } }); 

每次我在callback里面用callback里面的callback来写这样的东西,我觉得我做错了什么。 我知道承诺和asynchronous节点库,但似乎如果这些解决scheme,他们应该是默认function。 我做错了什么,还是只是不为我点击?

编辑:一些build议包括使用函数的callback,但似乎更糟糕的(除非我做错了,这是完全可能的)。 你最终在另一个里面调用一个函数,而且看起来特别是意大利式面条。

上面的例子,function:

 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 }); }); } }); 

asynchronous函数和callback的目的是为了避免在对象之间发生任何冲突(可能比您想象的更多)。

我想指出你对这个asynchronous爱好者: http : //www.sebastianseilund.com/nodejs-async-in-practice

是的,callback确实需要一些帮助,但这是值得的!

简而言之:而不是

 foo(function () { // ... stuff #1 ... bar(function () { // ... stuff #2 ... baz(); }); }); 

 foo(handleFoo); function handleFoo() { // ... stuff #1 ... bar(handleBar); } function handleBar() { // ... stuff #2 ... baz(); } 

当然,它可以(也许应该)更加细化,但这取决于实际的代码。 这只是一个避免嵌套函数的模式。 您也可以更多地使用这些方法。

这是“香草”的方法。 还有一些库可以让你以很好的方式pipe理它。

如果您觉得厌倦了无休止的callback,请尝试Q或CO 。 你可以这样编写node.js代码:

 co(function *(){ var a = get('http://google.com'); var b = get('http://yahoo.com'); var c = get('http://cloudup.com'); var res = yield [a, b, c]; console.log(res); })() 

这几乎是一种不同的写作方式,所以很难把握,但结果是相当不错的。