首页 文章

绑定Mongoose模型在async.auto(NodeJs)中保存方法

提问于
浏览
3

现在我正在使用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 将保存功能绑定到它应保存的对象 . 它在 async.seriesasync.parallel 中运行良好,但在 async.auto 中运行不佳 .

async.auto 将对象保存到数据库,但它会丢失回调并停止处理 . 但有没有人有任何想法 why it happens?

最奇怪的是,我从来没有遇到任何问题,既没有绑定 async.auto 内的任何其他内容,也没有绑定 Mongoose 保存方法在任何其他上下文中 .

我已经查看了 async 代码,但我仍然不知道's wrong. Now I'计划在github上写一个关于它的问题 .

Added 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!

所以问题深深地与mongoose save 功能相关联 .

当它与Mongoose方法 save 一起使用时,它看起来像 async.auto . 但我无法理解在哪里以及为什么 .

1 回答

  • 2

    编辑

    弄清楚:如果你使用@dpatti 's branch, it works. I guess @caolan hasn' t合并它(它在我们的Node.js框架中使用async 's been 6 months or so). I' m,Sails,所以我'll be keeping a close eye on this, so if it gets merged in, I'将在这里发布 .

    解决方案

    在package.json中,将您的异步依赖项更改为如下所示:

    "async": "git://github.com/dpatti/async.git#safe-auto"
    

    然后做一个 npm install ,你应该好好去 .


    与Sequelize的save()结合时遇到同样的问题 . 我认为这是一个函数上下文问题 - 希望有助于作为一个开始!

    我正在研究一个打破的基本示例,当有更多信息时我会报告 . 如果它看起来确实是异步中的问题,我将在github中提出一个问题并在此处链接到它 .

    我也在使用原始javascript(没有咖啡)的异步0.1.22(以及Sequelize 1.5.0-beta-2,以防任何人)

相关问题