Search code examples
node.jsfirebasefirebase-realtime-databasepromisechaining

Chaining and passing result of promise to a promise further down


I am chaining a few requests that return promises. The first one is a login check on some site that returns some credentials back. Then I making a admin.auth().createUser() call. After I know that this createUser call succeeds and that I know the login check succeeded, I want to use these two objects returned from both promises to make a third request to store information in firebase realtime database. I just dont know how to pass both those results to the final promise. Here's some code.

login(siteUser, sitePass)
   .then(credentials => {
      return admin.auth().createUser({
         'email': email,
         'emailVerified': false,
         'password': password,
         'displayName': username
       })
    })
    .then(userData => {
       return writeUserData(userData, credentials); // I need to pass credentials here but I don't know how.
    })
    .then(() => res.status(200).send('success'))
    .catch(err => res.status(500).send(err));

I need to pass the result from the first promise to writeUserData after createUser() resolves.


Solution

  • This is functionally equal to your code, except it passes credentials on to where it's needed for writeUserData. Rather than a completely flat promise chain, you add a .then to createUser response to return credentials rather than the unused (in your code) response from createUser

    login(siteUser, sitePass)
    .then(credentials => 
        admin.auth().createUser({
            email, 
            emailVerified:false, 
            password, 
            displayName: username
        })
        .then(userData => credentials)
    )
    .then(credentials => writeUserData(userRecord, credentials))
    .then(() => res.status(200).send('success'))
    .catch(err => res.status(500).send(err));
    

    If, however, you've made a mistake in your code and

    .then(userData => {
       return writeUserData(userRecord, credentials); // I need to pass credentials here but I don't know how.
    })
    

    was supposed to be

    .then(userData => {
       return writeUserData(userData, credentials); // I need to pass credentials here but I don't know how.
    })
    

    (i.e. userRecord should've been userData) - then you are not ignoring the response from createUser - this doesn't make the code much more complex at all

    login(siteUser, sitePass)
    .then(credentials => 
        admin.auth().createUser({
            email, 
            emailVerified:false, 
            password, 
            displayName: username
        })
        .then(userData => ({userData, credentials}))
    )
    .then(({userData, credentials}) => writeUserData(userData, credentials))
    .then(() => res.status(200).send('success'))
    .catch(err => res.status(500).send(err));