gpt4 book ai didi

javascript - Firebase .orderByChild().equalTo().once().then() 当 child 不存在时 promise

转载 作者:IT老高 更新时间:2023-10-28 23:07:10 26 4
gpt4 key购买 nike

我的 API /auth/login 端点采用 req.body 像这样:

{
"email": "jacob@gmail.com",
"password": "supersecretpassword"
}

在端点,我引用了我的 Firebase 数据库 (https://jacob.firebaseio.com/users)。我搜索数据,当我找到一个用户的电子邮件与 req.body.email 匹配时,我将密码与存储在数据库中的密码进行比较。

我遵循了 in this Firebase blog post 概述的 promise 结构.

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;
});
});

如果在 ref 处没有找到子 Node ,则函数不会继续执行(参见 this answer)。我什至没有抛出错误。

我的目标是在找不到用户使用特定电子邮件时运行代码(即在 ref 处找不到满足 .equalTo(req.body.email) 的 child >),但如果找到用户,则不运行代码。没有找到任何东西时不会抛出错误。

我尝试在调用数据库的关键点添加 return 语句(在我的 .then() promise 的末尾),目的是打破完全在代码运行后的端点。然后我在调用数据库之后放置代码:

    .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;
});

但无论对数据库的调用是否成功,此代码都会运行,因为调用是异步的。

如果对数据库的调用没有返回任何内容并且仍然使用 Firebase promise ,我该如何应对?

最佳答案

child_added 事件仅在查询与 users 下的至少一个键匹配时触发,如果有多个匹配项将触发多次。

您可以改用 value 事件 - 它只会触发一次,并且它的快照将包含 users 下匹配或将具有 value 的所有键 of 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',
)};
}
});
});

关于错误的处理,你可以像这样连接 Promise 并表达错误处理:

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);
});

关于javascript - Firebase .orderByChild().equalTo().once().then() 当 child 不存在时 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39176070/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com