Skip to content
This repository was archived by the owner on Sep 20, 2025. It is now read-only.
This repository was archived by the owner on Sep 20, 2025. It is now read-only.

Nested Promise #21

Description

@johncokos

return fetch( `slate-users/${user.username}`, {

    Auth.currentAuthenticatedUser()
      .then(user => {
        this.signedIn = true
        this.$store.commit('createUser', user)
        return fetch( `slate-users/${user.username}`, {
          method: 'GET',
          mode: 'cors'
        })
          .then(response => response.json())
          .then(apiObject => {
            this.$store.commit('setLanguageName', apiObject.languagePref)
            this.$store.commit('setLanguageCode', allLanguages.get(apiObject.languagePref))
            this.$store.commit('setCurrentRoom', apiObject.roomId)
          })
      })
      .catch(() => this.signedIn = false)
  }

Code like the above, while it works for sure in JS is part of the reason why JS has the reputation that it does. Use the SRP when you can as you would with Java to make that a little bit cleaner.

    Auth.currentAuthenticatedUser()
      .then(user => {
        this.signedIn = true;
        this.$store.commit('createUser', user);
        return this.getUser(user.username);
      })
      .catch(() => this.signedIn = false)
  }

  // this returns a promise to the caller
  const getUser = (userName) => {
    return fetch( `slate-users/${user.username}`, {
      method: 'GET',
      mode: 'cors'
    })
    .then(response => response.json());
    .then(abiObject => this.updateUserState(apiObject));
  };

  // Pull out the update user functionality.  This function isn't tied to the promise chain
  // So ... you could call it again if things change some reason (user changes a pref)
  const updateUserState = (data) => {
      this.$store.commit('setLanguageName', data.languagePref)
      this.$store.commit('setLanguageCode', allLanguages.get(data.languagePref))
      this.$store.commit('setCurrentRoom', data.roomId)
  };

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions