I`m learning q.js and trying to query 3 collections simultaneously with its help (avoiding callback hell):
var Q = require('q')
var deferred = Q.defer();
users() is a wrapper of db.collection.find()
var users = function (){
Auth.listUsers({role:'user'}, call)
return deferred.promise
}
call() is a shorthand for exporting promises
var call = function (err,data){
if (err) {
deferred.reject(err);
} else {
deferred.resolve(data);
}
}
loop() is main loop, which gets cursor and loops through entries
var loop = function (result) {
var list = []
var promises = [];
result.each(function (err,data){
if (err) {
deferred.reject(err);
} else {
deferred.resolve(data);
promises.push(deferred.promise)
console.log('promises_:', promises) // <- internal
}
})
console.log('promises:', promises) // <- external
return Q.all(promises)
}
code:
users()
.then(loop)
.then(function(ful){
console.log('ful:', ful); // <- here should come the queries to other collections
})
result of console logging at the end:
promises: [] //external is empty
ful: []
promises_: [ [object Object] ] // internal is being filled
promises_: [ [object Object], [object Object] ]
As you can see, the callback of .each is executed later than pushing promises to array.
I believe it can be made by using result.toArray() instead of .each, but how can it be done with the help of .each loop?
result is a cursor, returned by mongodb driver after db.collection.find() call (http://mongodb.github.io/node-mongodb-native/api-generated/collection.html#find).
each()from? Have you tried it with the Javascript functionforEach()? It might work better for you. Also, I'm not sure that I follow theresult.each()call having thefunction (err,data)does youreachcall with an error?deferredvariables from?.each()method is getting executed asynchronously, but isn't part of your promise scheme. You might want to useQ.ninvoke,Q.denodeify, or some similar strategy so that theeach()is returning a promise. Also, and I know you are clearly stripping out some code, but as written, you just have onedeferredyou are operating on. Inside your loop, you are just populating the array with multiple copies of the same promise, which in the line prior line you are resolving..each()is async. Couldn't understand theQfunctions (.fcall,.ncall, etc.). Can you recommend a good tutorial or a detailed manual on this library? I was not satisfied with its homepage.