承诺条纹 API

Promisifying the Stripe API

我正在尝试 util.promisify 以下确实成功的条纹调用:

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

IIUC 这应该有效:

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))

然而,当我 运行 以上时,我得到:

(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


create 似乎希望 this 在被调用时成为 stripe.customers,所以你需要 bind 它:

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

如果经常出现这种情况,您可以给自己一个效用函数:

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

然后

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

但请注意 .

Stripe 的 Node SDK,stripe-node,已经 returns 承诺,所以 你不需要承诺它

来自the docs

Every method returns a chainable promise which can be used instead of a regular callback:

只需省略 error-first callback

stripe.customers.create({
  description: 'My First Test Customer (created for API docs)'
})
.then(result => console.log(result))

或使用async/await:

const result = await stripe.customers.create({
  description: 'My First Test Customer (created for API docs)'
})
console.log(result)