I've read this post but my problem is not that.I was writing my functions needed for mongoDB GridFS management. I faced a very strange behaviour which I'm going to show you a simplified example of that. As you know, we use the callback function a lot. In my simplified example, everything works fine. The thing is that I want to update a local variable with the value that comes from the callback function:
function secondFunction(input, callbackFunction) {
var result = input + 5;
callbackFunction(result);
}
function thirdFunction(input, callbackFunction) {
var result = input + 5;
callbackFunction(result);
}
function mainFunction(input) {
var Answer = 0;
secondFunction(input, function (result) {
thirdFunction(result, function (result) {
Answer = result;
})
});
console.log(Answer);
}
mainFunction(5);
The result as you expect is 15. The Answer global variable has been updated successfully. But my problem is the code below which seems that the local variable has not been changed. In this example I wanted to get my images one by one from the gridFS and push them into an array called images (which is the local variable):
function getAll(callback) {
var images = [];
db.collection('fs.files').find({}).toArray(function (err, files) {
var Files = files;
for (var i = 0; i < Files.length; i++) {
getFileById(Files[i]._id, function (err, img) {
if (err) {
callback(err, null);
}
else images.push(img);
})
}
});
console.log(images);
}
The result is an [] array. What mistake am I making?
Edit:
function getFileById(id, callback) {
gfs.createReadStream({_id: id},
function (err, readStream) {
if (err) callback(err, null);
else {
if (readStream) {
var data = [];
readStream.on('data', function (chunk) {
data.push(chunk);
});
readStream.on('end', function () {
data = Buffer.concat(data);
var img = 'data:image/png;base64,' + Buffer(data).toString('base64');
setTimeout(function () {
callback(null, img);
}, 2000);
})
}
}
});
}
function getAll(callback) {
var images = [];
db.collection('fs.files').find({}).toArray(function (err, files) {
var Files = files;
for (var i = 0; i < Files.length; i++) {
getFileById(Files[i]._id, function (err, img) {
if (err) {
callback(err, null);
}
else images.push(img);
})
}
});
console.log(images);
}