我可以在不深度嵌套代码的情况下执行许多异步数据库请求吗?

Nic*_*ynt 2 asynchronous node.js coffeescript

我是异步编程的新手.我遇到了需要在循环中执行8次数据库查找的情况.我不知道如何实现这一点 - 我的数据库库在回调函数中返回数据,在我有所有8行之前我无法继续使用我的代码,因此我需要暂停直到所有8次查找完成.

这就是我现在所描绘的:

db.world.Queue.find(@user.kingdom.troops_queue).on 'success', (troops_queue) ->
    db.world.Queue.find(@user.kingdom.tanks_queue).on 'success', (tanks_queue) ->
        #etc etc
Run Code Online (Sandbox Code Playgroud)

当然这很可怕而且很糟糕,但是我想不出一种方法可以将它汇总到一个循环中,这个循环将允许我的代码暂停并且只在最后一个项目被填充时才继续.我正在研究像jQuery的.each()函数这样的东西,但该函数的行为是什么?它之后的代码会立即继续,还是等待循环完成?

the*_*ejh 9

有两种常用的方法.第一个是使用像caolans async这样的库:

async.parallel
  a: (cb) -> doTaskA cb
  b: (cb) -> doTaskB cb
, (err, {a, b}) ->
  # you can use err, a and b here now
Run Code Online (Sandbox Code Playgroud)

第二种方法是streamlinejs:

troops_queue = db.world.Queue.find(@user.kingdom.troops_queue).on 'success', _
tanks_queue = db.world.Queue.find(@user.kingdom.tanks_queue).on 'success', _
# go on here
Run Code Online (Sandbox Code Playgroud)

但是,两种解决方案都假设回调的第一个参数是错误 - 如果不是这样,你应该对你用来改变它的库的作者进行错误处理.

  • 'async`为+1.`async`除了`parallel`之外还有很多功能:`waterfall`,`forEach`等等,如果你正在编写异步代码,所有这些功能都非常有用. (3认同)