【问题标题】:How to stop function execution inside nested promises如何在嵌套的 Promise 中停止函数执行
【发布时间】:2018-07-24 17:20:17
【问题描述】:

我是 promise 的初学者,我正在尝试了解如何使用它们。

我有一个 firebase 触发器,我正在执行一些验证。如果验证失败,我想“退出”触发器,这意味着我不希望验证后执行任何代码(假设验证失败)。但确实如此。即使我确定验证失败(“您由于不活动而超时。请返回床位预订地图并重新开始”发送到我正在开发的android应用程序),之后的代码保留执行。我知道这一点是因为我在其中放置了控制台日志。

我已将 cmets 放入我的代码中,用于我正在谈论的验证,以及我不想执行的代码。

exports.createCharge = functions.database.ref('/customers/{userId}/charges/{id}')
  .onCreate((snap, context) => {
    console.log("Entered createharge function");
    const val = snap.val();
    return admin.database().ref(`/customers/${context.params.userId}/customer_id`)
      .once('value').then((snapshot) => {
        return snapshot.val();
      }).then((customer) => {

        // Do stuff

        if (val.type === 'beds') {
          // Check if user email is the same as bed email
          for (var i = 0; i < val.beds.length; i++) {
            var bedEmailRef = db.ref(`beds/${val.hid}/${val.beds[i]}/email`);
            bedEmailRef.on("value", function(bedEmailSnap) {
              var bedEmail = bedEmailSnap.val();
              if (val.email !== bedEmail) { // VALIDATION
                snap.ref.child('error').set("You have been timed out due to inactivity. Please go back to the bed booking map and start again"); 
                return null; // Here, I want to exit the whole function. 
              }
            });
          }

          // If val.email !== bedEmail, I NEVER want to reach here!
          return admin.database().ref(`/hotels/${val.hid}/bedPrice`)
            .once('value').then((tempBedPrice) => {
                // do stuff
              console.log("got here");
              return stripe.charges.create(charge, {idempotency_key: idempotencyKey});
            }).then((response) => {
              // Do more stuff
              return snap.ref.set(response);
            }).catch((error) => {
              snap.ref.child('error').set(userFacingMessage(error));
              return reportError(error, {user: context.params.userId});
            })

        } else throw Error('No type');
      });
  });

为什么我会出现这种行为?验证后如何停止代码执行?

【问题讨论】:

    标签: javascript node.js firebase firebase-realtime-database triggers


    【解决方案1】:

    问题是您在检查“床”类型后添加了一个“侦听器”。一个解决方案是fetch data once:

     // This is a snippet from Firebase documentation
     return firebase.database().ref('/users/' + 
       userId).once('value').then(function(snapshot) {
          var username = (snapshot.val() && snapshot.val().username) || 
         'Anonymous';
         // ...
     });
    

    或者重构你的代码,这样你的验证可以设置为一个回调,如果满足某些条件就可以返回。

    另外,这里有一个link for Cloud functions best practices,可以帮助你编写更好的云函数。

    【讨论】:

      【解决方案2】:

      如果您想退出/不再需要监听器上的事件,请重构您的代码,如下所示:

             bedEmailRef.on("value", function(bedEmailSnap) {
                var bedEmail = bedEmailSnap.val();
                if (val.email !== bedEmail) { // VALIDATION
                  snap.ref.child('error').set("You have been timed out due to inactivity. Please go back to the bed booking map and start again"); 
                  bedEmailRef.off('value'); // This will stop listening for further events
                  return null; // This is useless because returning inside a listener has no effect
                }
              });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-05-23
        • 2017-10-11
        • 1970-01-01
        • 2019-01-09
        • 2015-03-15
        • 1970-01-01
        • 2021-06-27
        • 1970-01-01
        相关资源
        最近更新 更多