Jac*_*cob 14 javascript node.js promise firebase firebase-realtime-database
我的API /auth/login端点采用req.body如下:
{
"email": "jacob@gmail.com",
"password": "supersecretpassword"
}
Run Code Online (Sandbox Code Playgroud)
在端点,我引用了我的Firebase数据库(https://jacob.firebaseio.com/users).我搜索数据,当我找到一个匹配电子邮件的用户时req.body.email,我将密码与存储在数据库中的密码进行比较.
我遵循了此Firebase博客文章中概述的承诺结构.
router.post('/login', function(req, res) {
const ref = db.ref('/users');
ref.orderByChild('email')
.equalTo(req.body.email)
.once('child_added')
.then(function (snapshot) {
return snapshot.val();
})
.then(function (usr) {
// Do my thing, throw any errors that come up
})
.catch(function (err) {
// Handle my errors with grace
return;
});
});
Run Code Online (Sandbox Code Playgroud)
如果找不到孩子ref,则该功能不会继续(请参阅此答案).我甚至没有抛出错误.
我的目标是在没有找到某个电子邮件的用户时运行代码(即没有找到ref满足的子级.equalTo(req.body.email)),但是如果找到用户则不运行代码.找不到任何内容时不会抛出任何错误.
我尝试return在数据库调用的战略要点(在我的.then()承诺结束时)添加语句,目的是在代码运行后完全断开端点.然后我在调用数据库之后输入代码:
.then(function (usr) {
// Do my thing, throw any errors that come up
})
.catch(function (err) {
// Handle my errors with grace
return;
});
res.status(401)
.json({
error: 'No user found',
)};
return;
});
Run Code Online (Sandbox Code Playgroud)
但是,无论对数据库的调用是否成功,都会运行此代码,因为调用是异步的.
如果它没有返回任何内容并且仍然使用Firebase承诺,我如何对此数据库的调用作出反应?
car*_*ant 25
该child_added事件只有在查询匹配下的密钥中的至少一个触发users,并会触发多次,如果有多个匹配.
您可以使用value事件,而不是-它会火只有一次,它的快照将包含所有的下键users匹配或会有value的null,如果没有匹配:
router.post('/login', function(req, res) {
const ref = db.ref('/users');
ref.orderByChild('email')
.equalTo(req.body.email)
.once('value')
.then(function (snapshot) {
var value = snapshot.val();
if (value) {
// value is an object containing one or more of the users that matched your email query
// choose a user and do something with it
} else {
res.status(401)
.json({
error: 'No user found',
)};
}
});
});
Run Code Online (Sandbox Code Playgroud)
关于错误的处理,您可以将承诺连接起来并表达错误处理,如下所示:
router.post('/login', function(req, res, next) {
const ref = db.ref('/users');
ref.orderByChild('email')
.equalTo(req.body.email)
.once('value')
.then(function (snapshot) {
...
})
.catch(next);
});
Run Code Online (Sandbox Code Playgroud)