I need to retrieve mutliple random data from my DB.
I have made a service in Sails.js for that purpose.
It's a Recursive function
- It generate a random number 0 to count of my DB.
- Stores the random number generated (All questions should be different)
- Get a random Question
- Store it in an array calling getQuestion And returning a promise
If the random generated array is smaller than the nb Result wanted : We call the function again
var RandomizerService= { // get a random single question // return a promise getQuestion: function (limit, skip){ var dfd = q.defer(); Question.find().limit(limit).skip(skip).then(function (question){ dfd.resolve(question); }); return dfd.promise; }, // Recursive function // Generate a random number 0 to count of my DB. // Stores the random number generated (All questions should be different) // Get a random Question and store it in an array calling getQuestion and returning a promise // If the random generated array is smaller than the nb Result wanted : // We call the function again questions: function (count, tabRes, tabRand, nbRes){ var dfd = q.defer(); rand = Math.floor(Math.random() * (count - 1)) + 1; if ( tabRand.indexOf(rand) === -1) { tabRand.push(rand); RandomizerService.getQuestion(-1, rand).then(function (result){ console.log(result[0]); // Is Returning AFTER the Randomizer.questions called in the Controller tabRes.push(result[0]); }); } if (tabRand.length<nbRes){ RandomizerService.questions(count, tabRes, tabRand, nbRes); } dfd.resolve(tabRes); return dfd.promise; } }; module.exports = RandomizerService;
When I'm calling this function in my Controller
RandomizerService.questions(count, [], [], 30).then(function (randQuestions){
console.log(randQuestions); // Return [];
});
randQuestions in returning an empty array.
But the console.log(result[0]); inside the getQuestions promise is returning AFTER the RandomizerService.questions (in Controller) promise ! oO
(When mocking the find() with a standard promise the whole system works).
Is there a probleme with Waternline or Sails ? What am I doing wrong ?
I'm using Sails.js 0.11 and I use sails.disk but I will use mongDB in the future :)
Thanks guys :)