【发布时间】:2012-09-07 20:24:07
【问题描述】:
现在我正在使用 mongoose 3.1.1 和 async 0.1.22。
但是当我尝试将 Mongoose 模型实例保存在 async.auto 中时,它就停止了工作。
看下面的例子,自己试试吧:
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 将保存函数绑定到它要保存的对象。它在async.series 和async.parallel 中效果很好,但在async.auto 中效果不佳。
async.auto 将对象保存到数据库,但它失去了回调并且处理停止。
但是有人知道为什么会发生吗?
最奇怪的是,我在绑定async.auto 内的任何其他内容以及在任何其他上下文中绑定Mongoose 保存方法时都没有遇到任何问题。
我已经查看了async 代码,但我仍然不知道出了什么问题。现在我打算在github上写一个关于它的问题。
添加 20.09.12: 我用 validate 函数替换了 save 函数,一切都很好:
running all tests
test 1
it works!
test 2
it works!
test 3
it works!
test 4
it works!
all works!
所以问题与猫鼬save函数有很深的关系。
看起来async.auto 在与 Mongoose 方法 save 一起使用时会在某处中断。但我不明白在哪里以及为什么。
【问题讨论】:
-
代码对我来说看起来不错。您是否检查了生成的 JavaScript 是否可能是 CoffeeScript 问题?
标签: node.js asynchronous coffeescript mongoose