Undefined values in array after promises:
I'm using Q to manage Promises with Node.js and I'm using easyImage to process images.
This block of code work fine, it load, save, cut images from tmp folder and paste it in the user folder. The only problem I have is to save the final data to the DB. I get undefined values within array...
exports.postAccountImages = function(req, res, next) {
User.findById(req.user.id, function(err, user) {
var path = __dirname + '/../public/images/u/' + user._id + '/';
var max = 800;
fs.exists(path, function(exists) {
if (!exists) fs.mkdirSync(path);
});
var promises = [];
for (var key in req.files) {
if (req.files.hasOwnProperty(key)) {
(function(file) {
q().then(function() {
return promises.push(easyimg.info(file.path).then(function(image) {
easyimg.resize({
src: file.path,
dst: path + file.name,
width: (image.width >= max) ? max : image.width,
height: (image.height >= max) ? max : image.height,
quality: 80
}).then(function(image) {
fs.remove('./tmp-uploads/' + image.name);
return {
src: image.name,
main: false
};
});
}));
});
})(req.files[key]);
}
}
q.all(promises).then(function(result) {
console.log(result); // [undefined, undefined, undefined, ...]
// Here I should push result to the DB
});
});
};