【问题标题】:Error: Meteor code must always run within a Fiber错误:Meteor 代码必须始终在 Fiber 中运行
【发布时间】:2015-03-02 09:36:36
【问题描述】:

我在我的应用程序中使用条带付款,我想在成功交易后在我自己的数据库中创建一个收据文档

我的代码:

Meteor.methods({
  makePurchase: function(tabId, token) {
    check(tabId, String);
    tab = Tabs.findOne(tabId);

    Stripe.charges.create({
      amount: tab.price,
      currency: "USD",
      card: token.id
    }, function (error, result) {
      console.log(result);
      if (error) {
        console.log('makePurchaseError: ' + error);
        return error;
      }

      Purchases.insert({
        sellerId: tab.userId,
        tabId: tab._id,
        price: tab.price
      }, function(error, result) {
        if (error) {
          console.log('InsertionError: ' + error);
          return error;
        }
      });
    });
  }
});

但是这段代码返回错误:

Error: Meteor code must always run within a Fiber. Try wrapping callbacks that you pass to non-Meteor libraries with Meteor.bindEnvironment.

我不熟悉 Fibers,知道为什么会这样吗?

【问题讨论】:

    标签: meteor


    【解决方案1】:

    您可能想查看http://docs.meteor.com/#/full/meteor_wrapasync 的文档。

    【讨论】:

    • 是的,但为什么我需要包装在 wrapasync 中?
    • 因为Stripe调用是异步的,但是你需要它是同步的,这样才能判断调用是否成功。
    【解决方案2】:

    这里的问题是你传递给Stripe.charges.create的回调函数是异步调用的(当然),所以它发生在当前Meteor的Fiber之外。

    解决此问题的一种方法是创建自己的Fiber,但您可以做的最简单的事情是用Meteor.bindEnvironment 包装回调,所以基本上

    Stripe.charges.create({
      // ...
    }, Meteor.bindEnvironment(function (error, result) {
      // ...
    }));
    

    编辑

    正如另一个答案中所建议的那样,这里要遵循的另一个可能更好的模式是使用Meteor.wrapAsync 辅助方法(请参阅docs),它基本上允许您将任何异步方法转换为可感知光纤并且可以同步使用。

    在您的特定情况下,等效的解决方案是编写:

    let result;
    try {
      result = Meteor.wrapAsync(Stripe.charges.create, Stripe.charges)({ /* ... */ });
    } catch(error) {
      // ...
    }
    

    请注意传递给Meteor.wrapAsync 的第二个参数。它可以确保原始 Stripe.charges.create 将收到正确的 this 上下文,以防万一需要。

    【讨论】:

    • 有人可以帮我吗?我和他有同样的问题,但我无法解决...有我的代码:jsfiddle.net/4k2LLa9v/1
    • @Jerome 我描述的第二种方法对你有用吗?
    猜你喜欢
    • 1970-01-01
    • 2017-10-03
    • 2017-08-16
    • 2013-12-01
    • 2018-01-16
    • 1970-01-01
    • 1970-01-01
    • 2015-03-28
    • 2018-04-07
    相关资源
    最近更新 更多