【发布时间】: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