如何在从Meteor.method返回之前等待子进程结果

时间:2012-04-20 17:55:19

标签: javascript mongodb coffeescript meteor

我很惊讶Meteor.method定义要求返回结果而不是调用回调。但事实就是如此!

我正在尝试在Meteor中创建一个调用mongoose组方法的RPC方法(它看起来不像meteor的数据api让我这样做所以我正在解决它)。我有这样的事情:

Meteor.methods
  getdata: ->
    mongoose = __meteor_bootstrap__.require('mongoose')
    db = mongoose.connect(__meteor_bootstrap__.mongo_url)
    ASchema = new mongoose.Schema()
    ASchema.add({key: String})
    AObject = mongoose.model('AObject',ASchema)
    AObject.collection.group(
      ...
      ...
      (err,doc) -> # mongoose callback function
         # I want to return some variation of 'doc'
    )
    return ??? # I need to return 'doc' here.

我自己对上面发布的代码的变化确实有效......我从我的流星客户端接到电话,猫鼬对象都发挥了他们的魔力。但我无法弄清楚如何让我的结果在原始背景下返回。

我该怎么做?


我接下来的答案会让我的代码看起来像这样:

require = __meteor_bootstrap__.require
Meteor.methods
  getdata: ->
    mongoose = require('mongoose')
    Future = require('fibers/future')
    db = mongoose.connect(__meteor_bootstrap__.mongo_url)
    ASchema = new mongoose.Schema()
    ASchema.add({key: String})
    AObject = mongoose.model('AObject',ASchema)
    group = Future.wrap(AObject.collection.group,6)
    docs = group.call(AObject,collection,
      ...
      ...
    ).wait()
    return docs

3 个答案:

答案 0 :(得分:4)

啊......想通了。在使用谷歌搜索和谷歌搜索,并发现大量的评论,沿着“不要这样做,使用回调!”,我终于找到它:使用fibers

我最终使用了fibers-promise库。我的最终代码看起来像这样:

Meteor.methods
  getdata: ->
    promise = __meteor_bootstrap__.require('fibers-promise')
    mongoose = __meteor_bootstrap__.require('mongoose')
    db = mongoose.connect(__meteor_bootstrap__.mongo_url)
    ASchema = new mongoose.Schema()
    ASchema.add({key: String})
    AObject = mongoose.model('AObject',ASchema)
    mypromise = promise()
    AObject.collection.group(
      ...
      ...
      (err,doc) -> # mongoose callback function
         if err
           mypromise.set new Meteor.Error(500, "my error")
           return
         ...
         ...
         mypromise.set mydesiredresults
    )
    finalValue = mypromise.get()
    if finalValue instanceof Meteor.Error
      throw finalValue
    return finalValue

答案 1 :(得分:2)

使用示例集合查看this amazing gist

答案 2 :(得分:0)

使用光纤/未来模块可能会为Meteor提供更好的API,因为这是内部使用的,它随附任何香草流星安装。

举个例子:

require  = __meteor_bootstrap__.require
Future   = require 'fibers/future'
mongoose = require 'mongoose'

Meteor.methods
  getdata: ->
    db = mongoose.connect(__meteor_bootstrap__.mongo_url)
    ASchema = new mongoose.Schema()
    ASchema.add({key: String})
    AObject = mongoose.model('AObject',ASchema)

    # wrap the method into a promise
    group = Future.wrap(AObject.collection.group)

    # .wait() will either throw an error or return the result
    doc = group(... args without callback ...).wait()