-1

I recently started learning JS and saw a tutorial on promises, and during a handson exercise i tried writing my own promise.



function isEven(number){
    return new Promise((resolve,reject)=>{
        res = "";
        if(isNaN(number)){
            reject();
            return res;

        }
        else{ 
            if(number%2 == 0){
                res= "Even";
            }
            res = "odd";
            resolve();
            return res;
        }
    })
}
var num = 45
let str = isEven(num).then(()=>{
    console.log("succesfull");
}).catch(()=>{
    console.log("NAN");
})
document.getElementById('number').innerHTML = str;

and the response i got [object Promise] . I want to access the str value which is returned through function isEven , kindly someone help me to understand this concept

1 Answers1

-1

Your problem is that, while you're resolving/rejecting the promise under certain conditions, there are no values associated with that action. You need to pass whatever you want to grab to those methods as below:

function isEven(number){
    return new Promise((resolve,reject)=>{
        res = "";
        if(isNaN(number)){
            reject(res)
        }
        else{ 
            if(number%2 == 0){
                res= "Even";
            }
            res = "odd";
            resolve(res)
        }
    })
}
var num = 45
let str = isEven(num).then(()=>{
    console.log("succesfull");
}).catch(()=>{
    console.log("NAN");
})
document.getElementById('number').innerHTML = str;

If you use the .then on a Promise it auto assumes that said Promise will resolve, taking that resolved value as input for whatever callback function you're putting inside

  • it is still showing [object promise] in the res variable . let me show the same thing i want to achieve in c++ as that's what i'm trying to achieve with js #include std::string isEvenOdd(int num){ if(num & 1) return "odd"; } return "even" } int main(){ int num = 45; std::string res = isEvenOdd(num); std::cout << res; return 0; – varun kumar Apr 15 '22 at 04:31
  • i found the answer now , thank you so much for helping. – varun kumar Apr 15 '22 at 04:49