错误:流星代码必须始终在光纤中运行 [英] Error: Meteor code must always run within a Fiber

查看:92
本文介绍了错误:流星代码必须始终在光纤中运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using stripe for payments in my app, I want to create a receipt document in my own database after a succesful transaction

我的代码:

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,为什么要这样呢?

I am not familiar with Fibers, any idea as to why this is?

推荐答案

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

The problem here is that the callback function which you pass to Stripe.charges.create is called asynchronously (of course), so it's happening outside the current Meteor's Fiber.

一种解决方法是创建自己的Fiber,但是最简单的方法是使用Meteor.bindEnvironment包装回调,因此基本上

One way to fix that is to create your own Fiber, but the easiest thing you can do is to wrap the callback with Meteor.bindEnvironment, so basically

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

编辑

如另一个答案中所建议,此处可能遵循的另一个更好的模式是使用Meteor.wrapAsync帮助器方法(请参见

Edit

As suggested in the other answer, another and probably better pattern to follow here is using Meteor.wrapAsync helper method (see docs), which basically allows you to turn any asynchronous method into a function that is fiber aware and can be used synchronously.

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

In your specific case an equivalent solution would be to write:

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

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

Please note the second argument passed to Meteor.wrapAsync. It is there to make sure that the original Stripe.charges.create will receive the proper this context, just in case it's needed.

这篇关于错误:流星代码必须始终在光纤中运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆