londonfed
londonfed

Reputation: 1230

Compacting multiple promises

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)
  })
},

Upvotes: 0

Views: 53

Answers (2)

Bergi
Bergi

Reputation: 664385

Error handlers that just rethrow the error are pointless, omit them.

You can unnest the outermost level with the usernameExist variable that you 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 with the nested then that ensures that user is returned in the end. There are a few approaches to tackle this problem, nesting closures is just fine.

Upvotes: 2

dfee
dfee

Reputation: 86

For multiple promises use

p1 = new Promise(); p2 = new Promise(); p3 = new Promise(); Promise.all([p1, p2, p3])

Promise.all documentation

Upvotes: 0

Related Questions