Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/meteor/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
错误:Meteor代码必须始终在光纤中运行_Meteor - Fatal编程技术网

错误:Meteor代码必须始终在光纤中运行

错误:Meteor代码必须始终在光纤中运行,meteor,Meteor,我正在我的应用程序中使用stripe进行支付,我想在成功交易后在我自己的数据库中创建一个收据文档 我的代码: Meteor.methods({ makePurchase: function(tabId, token) { check(tabId, String); tab = Tabs.findOne(tabId); Stripe.charges.create({ amount: tab.price, currency: "USD",

我正在我的应用程序中使用stripe进行支付,我想在成功交易后在我自己的数据库中创建一个收据文档

我的代码:

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.

我不熟悉光纤,你知道这是为什么吗?

你可能想看看文档。

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

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

Stripe.charges.create({
  // ...
}, Meteor.bindEnvironment(function (error, result) {
  // ...
}));
编辑 正如在另一个答案中所建议的,这里要遵循的另一个可能更好的模式是使用
Meteor.wrapAsync
helper方法(请参阅),它基本上允许您将任何异步方法转换为光纤感知的函数,并且可以同步使用

在您的具体情况下,等效的解决方案是:

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

请注意传递给Meteor.wrapAsync的第二个参数。它是为了确保原始的
Stripe.charges.create
将接收到适当的
上下文,以备需要。

是的,但为什么我需要用wrapasync包装?因为Stripe调用是异步的,但是你需要它是同步的,这样你才能确定呼叫是否成功。这里有人可以帮我吗?我和他有同样的问题,但我无法解决。。。这是我的密码:@Jerome我描述的第二种方法对你有用吗?