After exploring the information in this particular post, it became evident that my issue was different. While working on creating functions for managing mongoDB GridFS, I encountered a perplexing behavior that I will illustrate through a simplified example. Callback functions are frequently utilized in these scenarios. In my simple example, everything seems to be functioning properly. However, I encountered a challenge when attempting to update a local variable with the value retrieved from a 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 expected result is 15. The global variable Answer was successfully updated. However, the issue arises when attempting to update a local variable as demonstrated in the following code snippet, where the local variable appears unchanged. In this case, I aimed to retrieve images one by one from GridFS and store them in an array named 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 empty 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);
}