0

I'm new to Node.js and I'm experimenting with it.

Since values from one promise are not available globally I'm trying a way to assign value to a variable that can be accessed anywhere down the chain.

What I found is the first block of code always ends in catch and second block works OK the only difference being assignment of value.

Can someone help me with this in doing it right way.

var test = (req,callBack)=>{
    var value;
    return querydb.checkstatus(req).then((result)=>{
        value = 1;
        return(result);
    }).then((result)=>{
        if(result!=null){
            callBack(null, value);
        }
    }).catch((errorMessage)=>{
        callBack({Msg:"From Catch"},null);
    })
};

var test = (req,callBack)=>{
    var value;
    querydb.checkstatus(req).then((result)=>{
        return(result);
    }).then((result)=>{
        if(result!=null){
            callBack(null, "from then");
        }
    }).catch((errorMessage)=>{
        callBack({Msg:"From Catch"},null);
    })
};
David
  • 15
  • 7
  • what global variable? – epascarello Nov 14 '18 at 20:52
  • `return(result);` return is not a method – epascarello Nov 14 '18 at 20:53
  • may not be the right term but in this case I've defined a var value that will be used in promise chains. – David Nov 14 '18 at 20:54
  • Seem to be going down the wrong path using promises. The function should return the `checkstatus` promise and not need a callback param. Then you can chain promises and errors will be passed down the chain and caught at the end of the chain – charlietfl Nov 14 '18 at 21:05
  • See [How do I access previous promise results in a `.then()` chain?](https://stackoverflow.com/q/28250680/1048572) for how to solve your original problem correctly. – Bergi Nov 14 '18 at 21:15

0 Answers0