【发布时间】:2015-02-17 18:25:46
【问题描述】:
我需要从我的数据库中检索多个随机数据。
为此,我在 Sails.js 中提供了一项服务。
这是一个递归函数
- 它会生成一个随机数 0 来计算我的 DB。
- 存储生成的随机数(所有问题应该不同)
- 获取随机问题
- 将其存储在调用 getQuestion 的数组中并返回一个承诺
-
如果随机生成的数组小于 nb 想要的结果:我们再次调用该函数
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;
当我在控制器中调用此函数时
RandomizerService.questions(count, [], [], 30).then(function (randQuestions){
console.log(randQuestions); // Return [];
});
randQuestions 在返回一个空数组。
但是console.log(result[0]); getQuestions 承诺在 RandomizerService.questions (在控制器中)承诺之后返回! oO
(当使用标准承诺模拟 find() 时,整个系统都可以工作)。
Waternline 或 Sails 有问题吗? 我做错了什么?
我正在使用 Sails.js 0.11,我使用sails.disk,但我将在未来使用 mongDB :)
谢谢大家:)
【问题讨论】:
标签: javascript node.js promise sails.js waterline