The async module is not functioning properly in node.js.

Asked 2 years ago, Updated 2 years ago, 40 views

Creating pagination. I am making a code that receives a page as a query string and loads DB as mongoose and throws it as a view accordingly.

var page = req.query.page,
    perPage = 10;
if(page||page!=0||page!=1||typeof page != 'undefined') page=1;

async.waterfall([
    function(callback){
        ModA.find({}, {_id:0}).limit(perPage).skip(perPage * page).sort({
            name: 'asc'
        }).lean().exec(function(err, items){
            callback(null, items);
        });
    },
    function(items, callback){
        ModA.count().exec(function(err, count){
            callback(null, items, count);
        });
    }
], function(err, items, count){
    async.map(items, function(items, callback){
        Band.find({id : items.parent_id}, {name: 1, _id: 0}).lean().exec(function(err, band){
            items.parent_id = band[0].name;
            console.log(items.parent_id); // check point A
        });
        callback(err, items);
    },function(err, items){
            console.log ('async.map result;') // Check Point B
            for(ind in items){
                console.log(items[ind].parent_id);
            }
        res.render('reg_product', {
            items: items,
            page: page,
            pages: count / perPage
        });
    });
});

To put it simply, this code is like this.

ModA receives documents that meet the conditions (page) as an array of items and passes them to callback --> Take the number of documents in ModA as count and turn it over to the next callback as shown in the items
--> Run async.map once more in the last result function, items.Updated by referring to the value in Band collection as parent_id
--> map.async results Send a response with values received from function to res.render

The problem is items.When I checked the parent_id, it was only partially updated (the value before the update is an integer and the new value is a string, so it is easy to compare.)
Seeing that the number of updates is different at that time, it seems to be an asynchronous problem, but it's the same if you try async.map, mapSeries, each, and forEachOf.

In addition, items at check points A and B for debugging purposes.When I tried to print out the parent_id, it was definitely updated at point A, but there are integer values at point B, and in addition to the order in which it is displayed, B comes out first and A comes out.

I wonder why and how it can be solved. Please give me a merciful answer.

node.js javascript

2022-09-21 23:19

1 Answers

I haven't used mongoose yet. Shouldn't we put the callback part in the async.map in the same block as the check point A?


2022-09-21 23:19

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.