Firebase Stripe(错误)承诺必须得到适当处理

时间:2018-11-23 12:02:52

标签: node.js firebase google-cloud-functions

我正在尝试使用firebase和stripe处理付款,并且在尝试将功能部署到云时遇到一个问题,说“必须妥善处理承诺。我知道这是一个tlint编译错误,但无法弄清楚为什么会触发该错误。

这是我的代码

import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';

admin.initializeApp(functions.config().firebase);

const stripe = require('stripe')(functions.config().stripe.testkey);

exports.stripeCharge = functions.firestore
.document('/payments/{userId}/mypayments/{paymentId}')
.onCreate((snap,event) => {
const payment = snap.data()
const userId = event.params.userId
const paymentId = event.params.paymentId

// checks if payment exists or if it has already been charged
if (!payment || payment.charge) return null;

return admin.firestore()
  .doc(`/users/${userId}`)
  .get()
  .then(snapshot => {
    return snapshot
  })
  .then(customer => {
    const amount = payment.price * 100 // amount must be in cents
    const idempotency_key = paymentId  // prevent duplicate charges
    const source = payment.token.id
    const currency = 'usd'
    const charge = {amount, currency, source}

    return stripe.charges.create(charge, { idempotency_key })
 })
 .then((charge) => {
   admin.firestore()//The error keeps referring me to this line
.collection('/payments').doc(userId).collection('mypayments').doc(paymentId)
    .set({
      charge: charge
    }, { merge: true })
 })
})

产生错误的行已在上面指出

2 个答案:

答案 0 :(得分:1)

实际上,对于最新版本的Cloud Functions,您没有义务在Promises链中包括catch()。运行Cloud Function的平台将自行处理错误。

根据这篇文章What could this be about? [TsLint Error: "Promises must be handled appropriately"],显然是TsLint(EsLint?)生成的错误。

但是,与TsLint检测到的“错误”无关,我认为您的Cloud Function可能会遇到问题,因为您不退回链条的最后承诺:

return admin.firestore()     //HERE YOU RETURN CORRECTLY
  .doc(`/users/${userId}`)
  .get()
  .then(snapshot => {
    return snapshot         //HERE YOU RETURN CORRECTLY
  })
  .then(customer => {
    const amount = payment.price * 100 // amount must be in cents
    const idempotency_key = paymentId  // prevent duplicate charges
    const source = payment.token.id
    const currency = 'usd'
    const charge = {amount, currency, source}

    return stripe.charges.create(charge, { idempotency_key })    //HERE YOU RETURN CORRECTLY
 })
 .then((charge) => {
   return admin.firestore()    //HERE, IN YOUR CODE, YOU DON'T RETURN
.collection('/payments').doc(userId).collection('mypayments').doc(paymentId)
    .set({
      charge: charge
    }, { merge: true })
 })
})

答案 1 :(得分:0)

最终弄清楚 每当您做一个promise函数时,它都必须以错误处理程序结尾,因此我通过使用简单的catch

来解决了这个问题。
.then((charge) => {
   admin.firestore()
    .collection('/payments').doc(userId).collection('mypayments').doc(paymentId)
    .set({
      charge: charge
    }, { merge: true })
    .catch(er=>{
        console.log(er);
        return er
    }
    )
 })