Reputation: 249
I am currently using the firebase functions to call the following doc from the database:
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' });
}
});
The code runs fine but there is a logged error, if the doc exists in the database:
TypeError: Cannot read property 'user' of undefined
I presume the promise is still running and I am a bit stuck on how to end it?
Any help would be grateful. Thanks.
Upvotes: 0
Views: 31
Reputation: 317372
Your second then
callback is going to get invoked in all situations. Sending the 400 response in the first callback isn't actually going to stop the promise from propagating to all of the following then
callbacks.
If you want to stop the chain of then
callbacks from executing, you should instead throw an error to get picked up by a catch
down the chain, skipping all the then
.
Upvotes: 1