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

标签 node.js asynchronous 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

这当然很可怕而且很恶心,但我想不出一种方法可以将它卷入一个循环,让我的代码暂停,只有在最后一个项目被填满时才继续。我正在研究 jQuery 的 .each() 函数之类的东西,但该函数的行为是什么?它之后的代码是立即继续,还是等待循环完成?

最佳答案

常用的方式有两种。第一个是使用类似 caolans async 的库:

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

第二种方法是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

但是,这两种解决方案都假定回调的第一个参数是错误 - 如果不是这样,您应该打扰您正在使用的库的作者来更改它。

关于node.js - 我可以在不深入嵌套代码的情况下执行许多异步数据库请求吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8115076/

相关文章:

node.js - cordova build 命令失败,退出代码 EACCES

javascript - 使用 Node.JS Mongoose 查找文档并将值插入到 MongoDB 中的数组中

javascript - 使用 NodeJS 保存填充模型

javascript - 异步 JavaScript 动态包含

javascript - React 方法中多次调用 setState() : How to make it work "synchronously"

javascript - Angular CoffeeScript 语法错误

javascript - 如何在coffeescript :的 Angular 非类 Controller 中使用 'this'

javascript - 使用 ajax 向 Node.js 服务器发送 POST 请求

node.js - linux/node.js 上的异步调用消耗了哪些资源

javascript - 如何让 Turbolinks 停止干扰我的 JS?