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

How to wait for sub process results before returning from Meteor.method

本文关键字:等待 子进程 结果 返回 method Meteor      更新时间:2023-09-26

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

我正在尝试在 Meteor 中制作一个调用猫鼬组方法的 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

啊...想通了。在谷歌搜索和谷歌搜索并找到大量评论之后,我终于找到了:使用纤维!

我最终使用了纤维承诺库。我的最终代码如下所示:

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

通过一组示例查看这个惊人的要点。

使用 fibers/future 模块可能会为您提供更好的 Meteor API,因为这是内部使用的 API,并且它随任何原版 meteor 安装一起提供。

举个例子:

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()