【问题标题】:UnExpected behavior in Q.nfcall and Q.defer for mongoose mongodb model.savemongoose mongodb model.save 的 Q.nfcall 和 Q.defer 中的意外行为
【发布时间】:2014-12-16 10:30:31
【问题描述】:

我正在尝试使我的猫鼬模型使用 Q 承诺异步保存。 当我使用 Q.nfcall 或使用 Q.defer() 连接时,我看到传递给我的承诺的结果对象的行为有所不同

值得注意的是,当使用 Q.defer() 时,我能够访问结果对象的所有属性,就像使用本机回调函数一样。 但是,当使用 Q.nfcall 时,所有属性都是未定义的。 更令人费解的是,记录这两个对象,我可以看到打印出来的整个 json 字符串。

这是代码(在咖啡脚本中)

Customer = new models.Customer({name: 'John Doe'})
console.log 'Customer.id' + Customer.id

deferred = Q.defer()
Customer.save((error, value) -> 
  deferred.resolve(value)
)

deferred.promise.then((customer) -> 
  console.log 'Deferred::customer.id: ' + customer.id
  console.log 'Deferred::customer.name: ' + customer.name
  console.log 'Deferred::customer: ' + customer)

Q.nfcall(Customer.save.bind(Customer)).then((customer) ->  
  console.log 'Qnfcall::customer.id: ' + customer.id
  console.log 'Qnfcall::customer.name: ' + customer.name
  console.log 'Deferred::customer: ' + customer)

这是输出

Qnfcall::customer.id: undefined
Qnfcall::customer.name: undefined
Qnfcall::customer: { __v: 0, name: 'John Doe', _id: 54461d5523867cc087ef4374 },0
Deferred::customer.id: 54461d5523867cc087ef4374
Deferred::customer.name: John Doe
Deferred::customer: { __v: 0, name: 'John Doe', _id: 54461d5523867cc087ef4374 }

我看不出我在这里做错了什么。任何帮助都非常感谢!

【问题讨论】:

    标签: node.js mongodb coffeescript mongoose q


    【解决方案1】:

    Mongoose docs看来,Model#save的回调有三个参数:错误、保存的对象和更新的行数:

    回调将接收三个参数,如果发生错误则为err,product为保存的产品,numberAffected在数据库中找到并更新文档时为1,否则为0。

    Q.nfcall 检测到回调的第三个参数,并使用数组[savedObject, numberAffected] 解析承诺,这样您就不会丢失numberAffected。见Q docs:

    请注意,如果 Node.js 风格的 API 使用多个非错误参数(例如 child_process.execFile)进行回调,Q 在进行翻译时会将这些参数打包到一个数组中作为 promise 的履行值。

    在 CoffeeScript 中,你可以使用解构参数来解压这个数组:

    Q.nfcall(Customer.save.bind(Customer)).then ([customer, rowsAffected]) ->  
      console.log 'Qnfcall::customer.id: ' + customer.id
      console.log 'Qnfcall::customer.name: ' + customer.name
      console.log 'Qnfcall::customer: ' + customer
      console.log 'Qnfcall::rowsAffected: ' + rowsAffected
    

    【讨论】:

    • 感谢您的回复。你是对的,我错过了 Q 文档的那一部分。这解决了它!
    猜你喜欢
    • 1970-01-01
    • 2013-04-21
    • 1970-01-01
    • 2019-05-03
    • 2018-01-13
    • 1970-01-01
    • 2017-01-10
    • 1970-01-01
    • 2018-05-22
    相关资源
    最近更新 更多