I am trying to call two functions one within another
commonService Components
function AddEmail(user) {
return auth.createUserWithEmailAndPassword(user.email,user.password);
//createUsers(user) this way of calling is working, but i don't want to invoke like this...
}
function createUsers(user) {
return db.collection("users").add({
firstName: user.firstName,
lastName: user.lastName,
address: user.address,
phoneNumber: user.phoneNumber,
email: user.email,
role: user.role,
});
}
register component
submits(e) {
e.preventDefault();
const { user} = this.state;
commonService.AddEmail(user)
.then(() => {
commonService.createUsers(user)
.then(() =>{//success})
.catch(err=> console.log(err));
})
.catch(err=> console.log(err));
}
The AddEmail
gets executed, but not the createUsers
. I've tried returning and chaining via then method too, still its not working, what am I missing?
Try the following with async / await
.
async submit(e){
e.preventDefault();
const { user} = this.state;
try {
const userEmailAdded = await commonService.AddEmail(user);
const userCreated = await commonService.createUsers(user);
} catch (err) {
console.log(err);
}
}
Make sure to return a promise in both the function calls. If the return value is not a promise, wrap it in a promise using the following code
function AddEmail(user) {
return new Promise((resolve, reject){
const createdUser = auth.createUserWithEmailAndPassword(user.email,user.password);
if(createdUser)
return resolve(createdUser);
else
return reject("Error in creating user.");
})
}
Check for any errors in console. If none, both calls passed.