0

I have a for-loop statement and an async MongoDB inside loop body. What I want to do is to make a find query from my MongoDB database, and push the result into an Array.

Here is the code:

function() arrResult() {
  var arr = [];
  for(...) {
    collection.find({ foo: i }, function (err, cursor) {
      arr.push(cursor);   
    }    
  }
  return arr;
}

But it's obvious that the return value of the function would be an empty Array.

I want to tackle this problem using Q module. Is there any solutions?

2 Answers 2

2

I want to tackle this problem using Q module. Is there any solutions?

Yes, promises are a very easy abstraction to deal with this. You can execute the queries in parallel, and collect their results with all.

In particular, with Q it would look like this:

function arrResult(…) {
    var promises = [];
    for (…)
        promises.push( Q.ninvoke(collection, "find", {foo: i}) );
    return Q.all(promises);
}

arrResult(…).then(function(arr) {
    …
}, function(err) {
    // first error, if any occured
});
Sign up to request clarification or add additional context in comments.

4 Comments

Great. Could you please complete it using Q.defer()?
@AfshinMehrabani: Why would I need to? One never uses Q.defer manually. Q.ninvoke and the other callback-function method perfectly avoid this.
Just for educational purposes.
I think that's pretty well covered in Using deferreds in the Q docs. You can translate the example with FS.readFile directly into one for collection.find
1

You need a sync mechanism that acts like a process gate. Each returning query has to arrive at the gate, e.g. decrements some counter and deposit its result. When all arrived at the gate, a final callback does return the collected results.

4 Comments

Interesting...do you have any examples of this? I'm pretty intrigued
I hand coded such, but it must exist in the Node.js ecosystem. gimme a moment.
@mvw: You're looking for async.js' parallel function… However, notice that OP wants to use Q.
@Bergi: yes. The q Solution i don't know.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.