简体   繁体   English

承诺:如何处理承诺链中间的错误

[英]Promises: How to handle errors in the middle of promises chaining

I'm currently chaining some promises from Firebase database with some other ones from Stripe api. 我目前正在将Firebase数据库中的某些承诺与Stripe api中的其他一些承诺链接在一起。 I would like to know what is the best way to handle the following situation: 我想知道什么是处理以下情况的最佳方法:

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

      })

I would do it like; 我会这样做的;

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM