R
R
Roman Sopov2015-11-02 09:29:04
MongoDB
Roman Sopov, 2015-11-02 09:29:04

How to wait in NodeJS for mongodb.forEach and subqueries and return the result?

I get data using find, go through it forEach, in each iteration I need to execute a subquery, add the results to an array and then return them to res.json({..}) ?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
B
bromzh, 2015-11-02
@bromzh

promise
UPD
Responding to comments here.
In promises (there are several implementations of them, but they all have the same essence) there is an all function that will return the result of the promises of all the promises passed to it. Like this
So you can create an array, at each step of the loop, wrap the response in a promise (if it is not a promise itself) and then pass everything to the all method. For example, see the end of the first answer
. Sample code is as follows:

var queue = [];
cursor.forEach(function (element) {
    queue.push(Promise.resolve(element));
});
Promise.all(queue).then(function(arrayOfResults) {
    // тут делаешь что-то с массивом результатов.
});

A
Alexey Ukolov, 2015-11-02
@alexey-m-ukolov

How can I make a function run only after another one has completed?

M
Misha Kogan, 2015-11-02
@Kogan4ik

Try the async module, very useful library https://github.com/caolan/async

R
Roman Sopov, 2015-11-02
@sopov

This is how it worked for me, is this the right solution or is it necessary differently?

cursor.forEach(function(doc) {
    var find = {
        pid: doc._id.toString()
    };
    function cnt() {
        return new Promise(function(resolve, reject) {
            self.Struct.find(find).count().then(function(count) {
                var kids = false;
                if(count > 0) {
                    kids = true;
                }
                resolve({
                    id:         doc._id,
                    value:      doc.name,
                    webix_kids: kids
                }); 
            });
        });
    }
    data.push(cnt());		
}, function(err) {
    if(err == null) {
        Promise.all(data).then(function(data){
            res.json({
                success: true,
                error:   0,
                data:    data,
                parent:  pid
            });
        })
    } else {
         reject(err);
    }
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question