更新为了清楚我正在寻找一种在迭代while循环之前'等待'或'睡眠'的方法。抱歉混淆。
我有一个for循环,我想知道在循环遍历每个值之前让Node.js等待的最佳方法。目前它只运行所有内容而无需等待或继续循环(这是Node.js的本质),但任何提示都会有所帮助!
// Loop through time period and populate database with sensor events
var startTime = moment().startOf('year').unix();
var endTime = startTime + (24*60*60)*7;
var item = {};
while ( startTime <= endTime ) {
for ( var i = 0; i < chance.natural({ min: 1, max: SENSOR_LIMIT}); i++ ) {
//sensors.forEach(function(item) {
item = {
id: sensors[i]['id'],
address: sensors[i]['address'],
geolocation: {
lng: sensors[i]['geolocation']['lng'],
lat: sensors[i]['geolocation']['lat']
},
type: SENSOR_EVENT_TYPE,
value: generator.generateRandomSensorEventValue(startTime),
created_at: new Date(moment.unix(startTime).toISOString())
};
event.save(item);
}
// Increment time based on interval
startTime = startTime + SENSOR_EVENT_INTERVAL;
}
我在下面添加了我的event.save(item)代码段:
var mongoose = require('mongoose');
var event = require('../models/event.js').event;
var recentEvent = require('../models/recentEvent.js').recentEvent;
// Create event
exports.save = function(data) {
var item = new event(data);
item.create(function (error, data) {
if (error)
console.log('*** Could not add record');
else
console.log('+++ Added record to the collection');
var item = recentEvent(data);
item.save(function (error, data) {
if (error)
console.log('*** Could not add record');
else
console.log('+++ Added record to the capped collection');
});
});
}