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
You might want to take a look at the docs for http://docs.meteor.com/#/full/meteor_wrapasync.
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) {
// ...
}));
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.