I'm facing a weird problem when I must set a value from a mongodb find callback function to an external variable. e.g:
p += '<tr style="width: 165px!important;">';
photos.forEach(function(photo) {
EventPhoto.findOne({ _photo: photo._id }, function(err, doc) {
if (doc.main) {
p += '<td class="center-text"><a href="#" class="main-photo-on" onclick="javascript:changeMainPhoto("' + photo._id + '");">destaque</a></td>';
} else {
p += '<td class="center-text"><a href="#" class="main-photo-off" onclick="javascript:changeMainPhoto("' + photo._id + '");">destaque</a></td>';
}
});
});
p += '</tr>';
Variable p is incremental by every photo, the problem is when EventPhoto.find(...) ends and the value is not signed, losing all content added(I checked). Unfortunately I can't develop the rest of code inside this callback function, so what's the way to assign this value even there is no a "super" operator or something like that?
Thanks!
This cannot work because you are starting asynchronous requests and you do not know when the return value arrives. Instead, you should aim to execute each lookup in sequence and once you reached the end, continue doing the work that needs to be doing. I believe in your case, this would be more or less the approach you are seeking for.
var p = '<tr style="width: 165px!important;">';
var i = -1;
var next = function() {
i++;
if (i < photos.length) {
var photo = photos[i];
EventPhoto.findOne({ _photo: photo._id }, function(err, doc) {
if (doc.main) {
p += '<td class="center-text"><a href="#" class="main-photo-on" onclick="javascript:changeMainPhoto("' + photo._id + '");">destaque</a></td>';
} else {
p += '<td class="center-text"><a href="#" class="main-photo-off" onclick="javascript:changeMainPhoto("' + photo._id + '");">destaque</a></td>';
}
next();
});
}
else {
p += '</tr>';
// TODO: Do remaining work.
}
}
next();
pretty sure u need a closure:
edit: Nope!
p += '<tr style="width: 165px!important;">';
photos.forEach(
(function(what){
return function(photo) { //this will be forEach's iterator fn
EventPhoto.findOne({ _photo: photo._id }, function(err, doc) {
if (doc.main) {
what += '<td class="center-text"><a href="#" class="main-photo-on" onclick="javascript:changeMainPhoto("' + photo._id + '");">destaque</a></td>';
} else {
what += '<td class="center-text"><a href="#" class="main-photo-off" onclick="javascript:changeMainPhoto("' + photo._id + '");">destaque</a></td>';
}
});
}; // end of fn being returned by closure to forEach()
})(p) // pass p into the closure so the callback remembers it
); // end of forEach call
p += '</tr>'; // this will be added before the callback fires