简体   繁体   中英

NODE.JS, MONGOOSE, JAVASCRIPT - value from promise doesn't even return null or undefined

Good day, I would like to know the bug behind my code,

so first I have this db.js code:

/** check if may fb_id */
module.exports.checkfbid =
    async(model, query) => {
        return new Promise((resolve, reject) => {
            if (!query) {
                query = {};
            }
            console.log("pumasok sa checkfbid"+ JSON.stringify(query));
            console.log("pumasok sa checkfbid" + query);
            model.find(query)
                .then(res => {
                    console.log("hindi pa napapalitan: "+res);
                    if(null){
                        resolve(null);
                    }else{
                        console.log("untouched: " + res);
                        resolve(res);
                    }

            })
            .catch(err => {
                console.log("rejected si branch" + err);
                reject(err);
                console.log(err);
                throw err;
            });
    });
}

and this controller.js code

const id_result = await usersessionDB.checkfbid(model, {fb_id: id});// store sa id_result
        console.log("id_result have: " + id_result);// log kung may nkukuha na laman
        if (id_result === null) {// kung null si id_result, create ka new user
              ...
            }
        } else {// else kung hindi null si id_result
              ...
        }

EDIT! Sample output of console.logs

样本输出

Please disregard the foreign, unreadable comments. As you can see, console.log("pumasok sa checkfbid"+ JSON.stringify(query)); displays my query from the controller, but when it went inside the promise query, I used

console.log("hindi pa napapalitan: "+res);
                    if(null){
                        resolve(null);
                    }else{
                        console.log("untouched: " + res);
                        resolve(res);
                    }

It doesn't display thing!? I've been stuck for almost 3 hrs.

Summing it up, my problem is how can I define if it's null or undefine if the value return by the promise doesn't return even null or undefine? Is it just blank? or is it the other way around, it's returning a value but what kind of value? blank? Thank you.

I'm not sure if you intended this, but you're running a conditional statement against null ( if(null) {... ) which will always produce a falsey response.

Did you mean if(!res) {... ?

A better approach is to remove your if statement and use: resolve(res ? res : null)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM