承诺:如何在promises链接中处理错误

时间:2018-03-26 19:31:38

标签: javascript promise

我目前正在使用Stripe api从Firebase数据库链接一些其他承诺。我想知道处理以下情况的最佳方法是什么:

   firebase.database().ref('orders').push(**a new order object**)
      .then((snap) => {
        //I get back the saved object from the database, and in particular its unique Id
        orderId = snap.key;
        //I then create a stripe Source
        return stripe.createSource({
          type: '....',
          amount: ...,
          currency: '....',
          ...
          metadata: {
            orderId: orderId
          }
        })
      })
      .then((result) => {
        //here is my problem!! 
        //the result of the stripe source creation is either a
        // a result.source -i.e. success- or a result.error 
        if (result.source) {
          //here I can continue the flow and return a value
        } else if (result.error) {
          // But here, ideally I should somehow emit an error that should be catched by the catch below. 
          //How to do that the correct way??
        }
      })
      .catch((err) => {

      })

1 个答案:

答案 0 :(得分:2)

我会这样做;

.then(r => r.source ? doSomethingWith(r.source)
                    : Promise.reject(r.error))
.catch(handleError);