Using async function calls in meteor 1.6


#1

How would someone use async function calls in meteor 1.6? The code snippet below is from my meteor 1.2 app.

var Future = Npm.require('fibers/future');

Meteor.methods({
	'createCustomer': function(customer) {
    var stripeCustomer = new Future();

    var user = Meteor.user();

    if (!user) {
      throw new Meteor.Error(655, 'Anonymous Users cannot access createCustomer() Method!');        
    }

    var secretKey = Meteor.settings.private.stripe.testSecretKey;
    var Stripe = StripeAPI(secretKey);

    Stripe.customers.create({
      source: customer.token,
      email: customer.email,
      shipping: customer.shipping
    }, function(error, customer) {
      if (error) {   
        stripeCustomer.throw(error);
      } 
      else {        
        stripeCustomer.return(customer);
      }
    });

    return stripeCustomer.wait();

  },
)}

#3

The Stripe API methods all return promises if you don’t feed them a callback parameter. With Meteor’s support for async/await, you can write clean sync style code and return the data from the method as you would normally.

Meteor.methods({
    async createCustomer(customer) {
        if (this.userId) {
            const secretKey = Meteor.settings.private.stripe.testSecretKey;
            const Stripe = StripeAPI(secretKey);
            
            const stripeCustomer = await Stripe.customers.create({
                source: customer.token,
                email: customer.email,
                shipping: customer.shipping,
            });
            
            return stripeCustomer;
        }
        throw new Meteor.Error(655, 'Anonymous Users cannot access createCustomer() Method!');
    },
});


#4

Hi - try putting

import Future from ‘fibers/future’ ;

at the top rather than “var Future = Npm.require( ‘fibers/future’ );”

Then the syntax in the function looks correct as it is.

–jw