Search code examples
javascriptnode.jspromisestripe-paymentses6-promise

Promisifying the Stripe API


I'm trying to util.promisify the following stripe call which does succeed:

stripe.customers.create(
  {
    description: 'My First Test Customer (created for API docs)',
  },
  function(err, customer) {
      console.log(customer)
  }
)

IIUC this should work:

const util = require('util')

const createCustomerPromise = util.promisify(stripe.customers.create)

createCustomerPromise(
{
    description: 'My First Test Customer (created for API docs)'
}
).then(customer=>console.log(customer))

However when I run the above I get:

(node:28136) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'createResourcePathWithSymbols' of undefined
    at /home/ole/Temp/stripetest/node_modules/stripe/lib/StripeMethod.js:27:12
    at internal/util.js:286:30



Solution

  • create seems to want this to be stripe.customers when it's called, so you'll need to bind it:

    const createCustomerPromise = util.promisify(stripe.customers.create.bind(stripe.customers))
    // −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^^^^^^^^^^^^^^^^^^^^^^^
    

    If that's coming up a lot, you might give yourself a utility function:

    function promisifyMethod(obj, name) {
        return util.promisify(obj[name].bind(obj));
    }
    

    Then

    const createCustomerPromise = promisifyMethod(stripe.customers, "create");
    

    But note that Nik Kyriakides says the Stripe API already supports promises.