Thursday, 11 May 2017

why mongoose queries dos not work when put inside promise function

My code is as shown below:

checkAndCreateUser(customer_id, email_id).then(result => {
        console.log("result is " + result);
    });

var checkAndCreateUser = function (custom_id, email) {

    return new Promise(function (resolve, reject) {
        if ((!custom_id) && (custom_id.trim() == '')) {
            var creatUser = new user();
            // creatUser._id = user_id;
            creatUser.ph_no = ph_no;
            creatUser.email_id = email;
            console.log("fn works");
            user.findOne({
                'email_id': email
            }, function (err, user) {
                console.log("db test");
                if (!user) {
                    creatUser.save(function (err, userInfo) {
                        if (err) {
                            reject("no id found");
                        } else {
                            customer_id = userInfo._id;
                            resolve(customer_id);
                        }
                    });
                } else {
                    customer_id = user._id;
                    resolve(customer_id);
                }
            });
        }
    });
}

Now what happens here is I am not able to successfully run db query. I am able to get console.log("fn works") printed , but it does not print console.log("db test"). So what exactly is going wrong?



via Mrugesh Thaker

No comments:

Post a Comment