javascript - Compacting multiple promises -
i have following javascript promise chain. works 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, believe signup function hard decipher because of nested levels. tried change following approach:
userpromise .then() .then() .then(); but couldn't working because user variable needs passed down chain. ideally, minimize code readability , use 1 catch() efficiency. ideas appreciated.
update: following feedback bergi, below 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) }) },
error handlers rethrow error pointless, omit them.
you can unnest outermost level usernameexist variable don't need anywhere else:
signup (data) { return onefunction(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); }); } there's nothing wrong nested then ensures user returned in end. there a few approaches tackle problem, nesting closures fine.
Comments
Post a Comment