Error: Meteor code must always run within a Fiber

后端 未结 2 918
终归单人心
终归单人心 2020-12-10 11:35

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

My code:

Meteor.method         


        
相关标签:
2条回答
  • 2020-12-10 12:03

    You might want to take a look at the docs for http://docs.meteor.com/#/full/meteor_wrapasync.

    0 讨论(0)
  • 2020-12-10 12:29

    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.

    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) {
      // ...
    }));
    

    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) {
      // ...
    }
    

    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.

    0 讨论(0)
提交回复
热议问题