Search code examples
javascriptjqueryecmascript-6es6-promise

Promise is rejecting even tho it is true


If lunchTime is true lunch object should be logged if false err should be.

The console is logging: Error: OOOOOPs
Even if I try to log the lunch object in the then statement it just logs the error message

My plan was to just manually switch the value of lunchTime to false so that I could test the resolve/reject part of promises, but it's running the catch part of the code even tho it should be resolving.

const lunchTime = true;
    
    function orderMeSomeFood() {
        return new Promise((resolve, reject) => {
            if (lunchTime === true) {
                let lunch = {
                    food: "BBQ",
                    drink: "Zen WTR"
                };
    
                resolve(lunch);
            }
            else if (lunchTime === false) {
        const err = new Error('OOOOOPs')
        reject(err);
    }
            }
        })
    };
    
    orderMeSomeFood().then(() => {
        console.log(resolve);
    }).catch(() => {
        console.log(Error('OOOOOPs'));
    })

Solution

  • resolve only exists within the promise, so when you do console.log(resolve); it's throwing an error, which is why you're seeing the OOOOOPs message.

    If you want to console.log the lunch variable, you should change your code to:

    orderMeSomeFood().then(lunch => {
        console.log(lunch);
    }).catch(() => {
        console.log(Error('OOOOOPs'));
    })
    

    const lunchTime = true;
        
        function orderMeSomeFood() {
            return new Promise((resolve, reject) => {
                if (lunchTime === true) {
                    let lunch = {
                        food: "BBQ",
                        drink: "Zen WTR"
                    };
        
                    resolve(lunch);
                }
                else if (lunchTime === false) {
            const err = new Error('OOOOOPs')
            reject(err);
                }
            })
        };
        
        orderMeSomeFood().then(lunch => {
            console.log(lunch);
        }).catch(() => {
            console.log(new Error('OOOOOPs'));
        })