I have the following JavaScript promise chain. It works as expected.
signUp (data) {
return oneFunction(username).then((usernameExist) => {
return firebaseAuth.createUserWithEmailAndPassword(data.email, data.password).then((user) => {
firebaseDb.ref('users/' + user.uid + '/public/').set(userData).then()
utils.updateUsernameMapping(data.username, user.uid).then()
return user.updateProfile({
displayName: data.displayName
}).then(function () {
return user
}, error => {
throw error
})
})
}).catch(error => {
throw error
})
}
However, I believe the signUp function is hard to decipher because of the nested levels. I tried to change it to the following approach:
userPromise
.then()
.then()
.then();
But I couldn't get it working because the user variable needs to be passed down the chain. Ideally, I would like to minimize this code for readability and use one catch() for efficiency. Any ideas appreciated.
UPDATE: Following feedback from Bergi, below is my updated code:
signUp (email, password, displayName, username) {
const userData = { username: username, lastLogin: Firebase.database.ServerValue.TIMESTAMP }
return utils.checkIfUserExists(username).then(usernameExist => {
return firebaseAuth.createUserWithEmailAndPassword(email, password)
}).then(user => {
return Promise.all([
firebaseDb.ref('users/' + user.uid + '/public/').set(userData),
utils.updateUsernameMapping(username, user.uid),
user.updateProfile({displayName})
]).then(() => user)
})
},