【问题标题】:Promisifying the Stripe API承诺 Stripe API
【发布时间】:2020-02-08 08:52:07
【问题描述】:

我正在尝试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


【问题讨论】:

  • Stripe SDK 已经返回 Promise。只需省略回调,即stripe.customers.create().then().catch()
  • @NikKyriakides - 鉴于问题的标题是“Promisifying the Stripe API”(特别是),我想说这符合答案。我会把它作为一个发布(带有相关的文档链接)。

标签: javascript node.js promise stripe-payments es6-promise


【解决方案1】:

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

来自the docs

每个方法都返回一个可链接的承诺,可以用来代替常规回调:

只需省略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)

【讨论】:

    【解决方案2】:

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

    但请注意Nik Kyriakides says the Stripe API already supports promises

    【讨论】:

      猜你喜欢
      • 2015-11-22
      • 2015-02-26
      • 1970-01-01
      • 2018-11-07
      • 2019-04-26
      • 2020-10-25
      • 2017-09-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多