0

I am woking on NodeJS project. I have defined a variable inside the function scope. The variable is assigned in the inner functions to some value. But, with the scope of outer function, the variable value is undefined.

Below is the code block,

 getOTP(to,1).then((docs) => {
            if(!Array.isArray(docs) || !docs.length){
                otp = createOTP(config.OTP.otp_secret);//OTP is set here
            }else{
                if(!isOtpExpired(docs[0].created)){
                    otp = docs[0].otp.otp_number;
                }else{
                    updateOtp(docs[0]._id,3).then((response)=>{
                        if(response.result.nModified == 1 && response.result.ok == 1 ){
                            console.log("Entered");
                            otp = createOTP(config.OTP.otp_secret);
                        }
                    },(error)=>{
                        console.error('The promise was rejected', error, error.stack); 
                    });
                }   
            }
        },(error) => {
            console.error('The promise was rejected', error, error.stack);
        });
        console.log('OTP',otp);//OTP is undefined

Please help me, how can I access the OTP value in the outer function. Any help will be appreciated.

  • 2
    `then` handlers are always called *asynchronously*. SO you're trying to output the variable before the value's been assigned to it. See the linked question's answers for more. – T.J. Crowder Aug 26 '18 at 16:16
  • 1
    Thank you very much @T.J.Crowder. I understood the issue. – Vikas Biradargoudar Aug 26 '18 at 16:19
  • 1
    It happen because of asynchronous behaviour of node js. If you really want to print the output after this promise execution, then you can use setTimeout. setTimeout(function(){ console.log(otp); },1000) – radhey shyam Aug 26 '18 at 18:50

0 Answers0