Sangram Badi
Sangram Badi

Reputation: 4274

how to handle expressJs callback and how to update object's property inside a function?

I have two js files. i am able to get data from mongodb by calliing bookDao.getActiveBookByCategoryId().

My Problem

In categoryDao.js file i am trying to update resultJson.book_countinside BookDao.getActiveBookByCategoryId() method. but it is not updating. So may i know how to fix this. here book_count property in resultJson is still 0.

categoryDao.js

module.exports.getAllActiveCategory = (callback) => {
    Category.find({
        is_delete : false
    }, (error, result) => {
        if(error) {
            console.log(error);
            callback(commonUtil.ERROR);
        }

        if(result) {
            var categoryArray = [];
            for(var i=0; i<result.length; i++) {
                var categorySingle = result[i];
                var resultJson = {
                    _id : categorySingle._id,
                    category_name : categorySingle.category_name,
                    created_on : categorySingle.created_on,
                    book_count : 0
                }

                BookDao.getActiveBookByCategoryId(categorySingle._id, (bookResult) => {
                    if(bookResult) {
                        if(bookResult.length > 0) {    
                            resultJson.book_count = bookResult.length;
                        }
                    }
                });
                categoryArray.push(resultJson);
            }
            callback(categoryArray);
        }
    });
}

bookDao.js

module.exports.getActiveBookByCategoryId = (categoryId, callback) => {
    Book.find({
        is_delete : false,
        category : categoryId
    }, (error, result) => {
        if(error) {
            console.log(error);
            callback(commonUtil.ERROR);
        }

        if(result) {
            callback(result);
        }
    });
}

Upvotes: 0

Views: 133

Answers (1)

Rahul Sharma
Rahul Sharma

Reputation: 10111

Try this, In your code categoryArray.push(resultJson); will not wait for BookDao.getActiveBookByCategoryId to finish because of async behavior.

module.exports.getActiveBookByCategoryId = (categoryId) => {
    return Book.count({
        is_delete: false,
        category: categoryId
    });
}


module.exports.getAllActiveCategory = async () => {
    try {
        // Find all category
        const result = await Category.find({
            is_delete: false
        });

        // Create array of promise
        const promises = result.map(categorySingle => BookDao.getActiveBookByCategoryId(categorySingle._id));
        // Get array of Category count
        const data = await Promise.all(promises);
        // update count in result
        return result.map((categorySingle, i) => {
            categorySingle.book_count = data[i];
            return categorySingle;
        });
    } catch (error) {
        console.log(error);
    }
}

Upvotes: 1

Related Questions