现在我正在使用 mongoose 3.1.1 和 async 0.1.22。
但是当我试图在 async.auto
中保存 Mongoose 模型实例时,它就停止工作了。
请看下面的例子,自己试一下:
mongoose = require 'mongoose'
async = require 'async'
Schema = mongoose.Schema
ObjectId = Schema.ObjectId
mongoose.connect "mongodb://localhost:27017/async-test"
SmthSchema = new Schema
data : type: String
mongoose.model 'Smth', SmthSchema
Smth = mongoose.model 'Smth'
test1 = (next) ->
console.log ' test 1'
smth = new Smth data: 'some data'
async.auto
first: (callback) ->
smth.save callback
second: ['first', (callback) ->
console.log ' it works!'
callback()]
next
test2 = (next) ->
console.log ' test 2'
smth = new Smth data: 'some data'
async.series [
smth.save.bind smth
(callback) ->
console.log ' it works!'
callback()
], next
test3 = (next) ->
console.log ' test 3'
context =
save: (callback) -> callback null
async.auto
first: context.save.bind context
second: ['first', (callback) ->
console.log ' it works!'
callback()]
next
test4 = (next) ->
console.log ' test 4'
smth = new Smth data: 'some data'
async.auto
first: smth.save.bind smth
second: ['first', (callback) ->
console.log ' it works!'
callback()]
next
console.log 'running all tests'
async.series [test1, test2, test3, test4], (err) ->
console.log err || 'all works!'
结果输出:
running all tests
test 1
it works!
test 2
it works!
test 3
it works!
test 4
smth.save.bind smth
将保存函数绑定(bind)到它要保存的对象。它适用于 async.series
和 async.parallel
,但不适用于 async.auto
。
async.auto
将对象保存到数据库,但它会丢失回调并停止处理。
但是有人知道为什么会这样吗?
最奇怪的是,无论是在 async.auto
中绑定(bind)任何其他内容,还是在任何其他上下文中绑定(bind) Mongoose
save 方法,我都没有遇到任何问题。
我已经研究过 async
代码,但我仍然不知道哪里出了问题。现在我打算在 github 上写一个关于它的问题。
2012 年 9 月添加:我用 validate
函数替换了 save
函数并且一切正常:
running all tests
test 1
it works!
test 2
it works!
test 3
it works!
test 4
it works!
all works!
所以这个问题与 mongoose save
功能密切相关。
看起来 async.auto
在与 Mongoose 方法 save
一起使用时在某处中断。但我不明白在哪里以及为什么。
最佳答案
编辑
弄明白了:如果您使用@dpatti 的分支,它就可以工作。我猜@caolan 还没有合并它(已经 6 个月左右了)。我在我们的 Node.js 框架中使用异步,Sails ,所以我会密切关注这一点,所以如果它被合并,我会发回这里。
解决方案
在您的 package.json 中,将您的异步依赖项更改为如下所示:
"async": "git://github.com/dpatti/async.git#safe-auto"
然后执行 npm install
就可以了。
在结合Sequelize的save()时遇到同样的问题。我认为这是一个函数上下文问题——希望这有助于开始!
我正在研究一个基本的例子,但我会在有更多信息时报告。如果看起来它实际上是异步中的问题,我将在 github 中提出问题并在此处链接到它。
我也在异步 0.1.22(和 Sequelize 1.5.0-beta-2,以防万一)使用原始 javascript(没有咖啡)
关于node.js - 在 async.auto (NodeJs) 中绑定(bind) Mongoose 模型保存方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12428439/