First and foremost I accept that this issue is not something new for developers and there are thousands of post in Stackoverflow.(Specially this post ) I'm new to web development. When I read those post I don't understand what they're saying. I need a very simple solution since I'm an amateur.
As you know sometimes you need to retrieve data from your database (in my situation it was MongoDB GridFS) and sometimes this cause problem.
The function below(getAll) is meant to retrieve all pictures in my GridFS, push them into an array (images) and finally, call the callback function with the answer:
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);
})
}
});
setTimeout(function () {
callback(null, images);
}, 1000)
}
At first, I didn't use setTimeout and Got the problem that my images array was always empty. But when I used the setTimeout function everything went smoothly. (It took almost a week to find this solution!)
I'm familiar with promises and what they mean and they usage (I use it a lot in AngularJs whenever I receive any answer from the server using $promise). Is it possible to use something like promises here? I used this approach but again doesn't work (the answer is again an empty array):
function getAll() {
return new Promise(function (resolve, reject) {
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) {
reject('error occurred');
}
else images.push(img);
})
}
});
resolve(images);
});
}
As I mentioned in this post, I successfully handled this issue with setTimeout but I think this way of handling is totally wrong since I don't know when the retrieval process is finished (here I choose 1 sec delay but in general you never know).
What is the best way to handle these kinds of behavior as they are so common?