Almaju
Almaju

Reputation: 1383

Meteor async function in method

I read everything concerning this issue and I must admit I am still pretty lost.

I have a payment system which need to do HTTP POST queries to validate payment.

So basically here is my code on the server:

Payment.sendPayment = function(callback){
    HTTP.post(..., function(err, result){
        if(err) throw new Error('This is an error!');

        callback && callback(null);
    });
}

With the method as follow:

Meteor.methods({
    buy: function(){
        Payment.sendPayment(function(err){
            if(err) throw new Meteor.Error('buy', err);
        });
    }
});

It does not work since the return is not in the main function. I tried with wrapAsync:

Meteor.methods({
    buy: function(){
        var sendPayment = Meteor.wrapAsync(Payment.sendPayment);

        console.log(sendPayment());
    }
});

Still does not work. I couldn't find any simple example of wrapAsync. I found some stuff concerning Future package but the posts were quite old.

Any idea to do this?

Thank you!

Upvotes: 1

Views: 60

Answers (1)

Hook
Hook

Reputation: 37

If you want to use futures, here is an example:

var Future = Npm.require('fibers/future');
Meteor.methods({
    buy: function(){
        var future = Future();
        Payment.sendPayment(function(err){
            if(err) {
                return future.return(err); //return the error
            }
            return future.return(); //you can return the result here if you want
        });
        return future.wait();
    }
});

Upvotes: 1

Related Questions