mmu36478
mmu36478

Reputation: 1355

Using waterfall in map node.js

async.map(map, function(item, mnext){
    async.waterfall([
        function(wnext){
            console.log("1"); 
            //mongodb queryies something like
            db.collection.find().toArray(function(err){
                if(err){
                    wnext(err);
                }else{
                    wnext();
                }

            })
        },
        function(wnext){
            console.log("2"); 
            //mongodb queryies something like
            db.collection.find().toArray(function(err){
                if(err){
                    wnext(err);
                }else{
                    wnext();
                }

            })
        },
        function(wnext){
            console.log("3"); 
            //mongodb queryies something like
            db.collection.find().toArray(function(err){
                if(err){
                    wnext(err);
                }else{
                    wnext();
                }

            })
        }   



    ], function(err){
        if(err){
            mnext(err);
        }else{
            mnext();
        }

    })
})

I expected to see 1 2 3 1 2 3 1 2 3 based on the count of the map. But the situation is not as what I expected. I realize that it prints as 1 2 1 2 3 3 or something else than 1 2 3. I couldn't understand how can this happen. Because it's waterfall and the structure is true I guess? So can we say that there is a problem about map or waterfall? Or it async.map is asynchronous so it overwrite the waterfall?

I don't know.. and I'm stucked. What am I missing?? Isn't 1 2 3 is expected sequence?

Upvotes: 0

Views: 148

Answers (1)

RaR
RaR

Reputation: 3213

If you see async.map doc https://caolan.github.io/async/docs.html#map,

Note, that since this function applies the iteratee to each item in parallel, there is no guarantee that the iteratee functions will complete in order

Yes. async.map is parallel. To achieve what you want, use async.mapSeries https://caolan.github.io/async/docs.html#mapSeries

Upvotes: 1

Related Questions