如何处理expressJs回调以及如何在函数内更新对象的属性?

时间:2018-07-19 04:54:29

标签: javascript node.js mongodb express callback

我有两个js文件。我可以通过调用bookDao.getActiveBookByCategoryId()从mongodb获取数据。

我的问题

在categoryDao.js文件中,我正在尝试更新resultJson.book_count内部的BookDao.getActiveBookByCategoryId()。但它没有更新。所以我可以知道如何解决这个问题。 这里book_count中的resultJson属性仍然为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);
        }
    });
}

1 个答案:

答案 0 :(得分:1)

尝试此操作,由于异步行为,在您的代码categoryArray.push(resultJson);中不会等待BookDao.getActiveBookByCategoryId完成。

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);
    }
}
相关问题