javascript - Firebase 函数承诺未定义的 TypeError
问题描述
我目前正在使用 firebase 函数从数据库中调用以下文档:
let token, userId;
db.doc(`/users/${newAccount.username}`)
.get()
.then((doc) => {
if (doc.exists === false) {
return firebase.auth().createUserWithEmailAndPassword(newAccount.email, newAccount.password).catch(err => console.error(err));
} else {
res.status(400).json({ username: 'this username is already taken' });
}
})
.then(data => {
userId = data.user.uid;
return data.user.getIdToken();
})
.then((idToken) => {
token = idToken;
const userCredentials = {
username: newAccount.username,
email: newAccount.email,
created: new Date().toISOString(),
userId
};
return db.doc(`/users/${newAccount.username}`).set(userCredentials);
})
.then(() => {
return res.status(201).json({ token });
})
.catch((err) => {
console.error(err);
if (err.code === 'auth/email-already-in-use') {
return res.status(400).json({ email: 'Email is already is use' });
} else {
return res.status(500).json({ general: 'Something went wrong, please try again' });
}
});
如果文档存在于数据库中,则代码运行良好,但会记录错误:
TypeError: Cannot read property 'user' of undefined
我认为承诺仍在运行,我对如何结束它有点困惑?
任何帮助将不胜感激。谢谢。
解决方案
您的第二个then
回调将在所有情况下被调用。在第一个回调中发送 400 响应实际上并不会阻止 Promise 传播到所有以下then
回调。
如果要停止then
执行回调链,则应改为抛出错误以被链下的 a 拾取catch
,跳过所有then
.
推荐阅读
- java - 在 java 正则表达式中,将 \ 替换为“如果正斜杠 / 后跟反斜杠 \ 则忽略
- jestjs - LatLngToLayerPoint 转换为像素坐标
- javascript - 捕获网络文件或客户端的网络请求
- android - 如何在 android studio 中设计 whatsapp 聊天气泡?
- javascript - 存在 Cookie 标头,但 Cookie 未存储在浏览器中
- json - 如何使 for 循环在 vue js 中正常工作
- r - 将多个文本文件合并到一个数据框中
- sql - 通过维护一个临时不断更新的表来实时计算从 A 到 B 的汽车的坐标之间的距离
- javascript - HTMLElement.click() 可以限制使用一定的次数吗?
- drake-r-package - R {drake}:如何将 .drake 文件夹从一台计算机克隆到另一台计算机?