Search code examples
javascripterror-handlingchainingmethod-chaining

How to .then chain but need the resolve() value from the previous promise - javascript?


The issue lies in the "backendLoginCheck" function. I want to .then() chain "ifUserIsDisabled" after "getUserByEmail". But I need the "userRecord" from getUserByEmail for the input into "ifUserIsDisabled".

I also want both functions to share the same .catch in "backendLoginCheck" function.

Current Code:

function getUserByEmail(email){
        return new Promise(function(resolve, reject){
        firebase.serverAuthAdmin147th.getUserByEmail(email)
            .then(function(userRecord) {
                resolve(userRecord);
            })
            .catch(function (error) {
                reject({token: null, errorCode: "auth/user-not-found"});
            });
    })
}

function ifUserIsDisabled(userRecord){
    return new Promise(function(resolve, reject){
        if(!userRecord.disabled){
            resolve();
        }
        else{
            reject({token: null, errorCode: "auth/user-disabled"});
        }
    })
}

function backendLoginCheck(email, password, callback){
    var token = null;
    var errorCode = null;
    var uid = null;
    getUserByEmail(email)
        .then(function(userRecord){
            ifUserIsDisabled(userRecord);
        })
        .catch(function(error){
            callback(error);
        });
}

Desired Idea:

...
getUserByEmail(email)
    .then(ifUserIsDisabled(userRecord))
    .then(nextFunction())
    .then(nextFunction2(uses_resolveVal_from_nextFunction))
    .then(nextFunctionEtc())
    .catch(function(error){
        callback(error);
    });

Solution

  • If I'm understanding you correctly, it looks like you're almost there. If a then chain in a promise returns another promise you can pass the resolved values down the chain

    for example:

    function firstFunction() {
       return new Promise((resolve, reject) => {
           if (someError) {
               reject(firstErr)
           } else {
               resolve('first value')
           }
       })
    } 
    
    function secondFunction() {
       return new Promise((resolve, reject) => {
           if (someError) {
               reject(secondErr)
           } else {
               resolve('second value')
           }
       })
    } 
    
    firstFunction()
      .then((resolvedFirstValue) => {
          return secondFunction()
      })
      .then((resolvedSecondValue) => {
          console.log(resolvedSecondValue)
      })
      .catch((err) => {
          // any error in the entire chain
          console.error(err)
      })