流星:在服务器端组织一个循环
问题描述:
我如何设法在流星的服务器端运行循环? 例如 我想每3秒钟向数据库添加一些内容。流星:在服务器端组织一个循环
for(var i = 0; i < 100; i++) {
setInterval(Meteor.bindEnvironment(function() {
post.type = types[getRandomInt(0,3)];
post.message = 'sometext';
post.timeCreated = new Date().valueOf();
post.source = sources[getRandomInt(0,1)];
Posts.insert(post);
console.log('New post was added.');
}, 1000));
}
但它没有任何意义:数据生成非常快,没有任何延迟。
答
因为你有什么错在你的setInterval
了解,你会发现它是如何工作的here
当你的代码,你写的循环,这等于叫setInterval
100次setInterval
。因此每次都会将100条记录插入到您的收藏中。
我可以给你一个在两种方式每秒插入记录到Post
的例子。
PS:我更喜欢使用Meteor.setTimeout和其他流星方法比Meteor.bindEnvironment
// First: only use setInterval
function insertPostsHandler(frequency) {
var count = 0;
// Meteor.setInterval would returns a handle
// which can be used by Meteor.clearInterval to stop it
var insertHandler = Meteor.setInterval(function() {
if (count++ < frequency) {
post.type = types[getRandomInt(0,3)];
post.message = 'some text';
post.timeCreated = new Date().valueOf();
post.source = sources[getRandomInt(0,1)];
Posts.insert(post);
console.log('New post was added.');
} else {
// stop the timer when count >= frequency
Meteor.clearInterval(insertHandler);
}
}, 1000); // insert a record nearly per second
}
// Second: use setTimeout
function insertPostsHandler(frequency) {
Meteor.setTimeout(insertPost, 1000, 0, frequency);
}
// You could also write directly, but I prefer to use a function holding it
// Because the code would be more clearly
// Meteor.setTimeout(insertPost, 1000, 0, frequency);
function insertPost(count, frequency) {
if (count < frequency) {
post.type = types[getRandomInt(0,3)];
post.message = 'some text';
post.timeCreated = new Date().valueOf();
post.source = sources[getRandomInt(0,1)];
Posts.insert(post);
console.log('New post was added.');
// call insertPost recursively when count < frequency
setTimeout(insertPost, 1000, ++count, frequency);
}
}
你可以使用其中任意一个插入后记录
我希望它可以帮助:-)
谢谢!真的解决了! –