错误:流星代码必须始终在光纤内运行

时间:2015-01-04 19:35:50

标签: meteor

我在我的应用中使用条形付款,我想在成功交易后在我自己的数据库中创建收据文件

我的代码:

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不熟悉,不知道为什么会这样?

2 个答案:

答案 0 :(得分:28)

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

解决这个问题的一种方法是创建自己的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上下文,以防万一需要。

答案 1 :(得分:5)

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