Meteor.method返回前如何等待子进程结果
·
问题:Meteor.method返回前如何等待子进程结果
我有点惊讶Meteor.method定义需要返回结果而不是调用回调。但事实就是如此!
我正在尝试在 Meteor 中创建一个调用猫鼬组方法的 RPC 方法(看起来流星的数据 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
解答
啊......想通了。在谷歌搜索和谷歌搜索并发现大量评论“不要那样做,使用回调!”之后,我终于找到了它:使用纤维!
我最终使用了fiber-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
更多推荐
所有评论(0)