Answer the question
In order to leave comments, you need to log in
How to return a value from a callback function?
There is a repository that returns a collection from mongo db
getProducts: function (callback) {
products.products.find({}, function (error, result) {
callback(error, result);
})
},
getAllProducts: function() {
var collection;
productRepository.getProducts(function(error, result) {
collection = result;
});
return collection;
}
Answer the question
In order to leave comments, you need to log in
Here the idea is that the productRepository.getProducts function will be executed instantly, and the callback function will be executed after some time. First, productRepository.getProducts will be executed, then return collection, and then only after a while callback with collection = result, but it will be too late.
Then decide what is best. It is possible asynchronously via callback (callback instead of return):
getAllProducts: function(callback) {
productRepository.getProducts(function(error, result) {
callback(error, result);
});
}
I can suggest that you probably do not understand what asynchrony is.
The getAllProducts function must either accept its own callback, on which the value received from the mongi will then be thrown, or give a promise, the differ of which will be resolved after collection = result.
Thus, nothing will work. Your collection will always be undefined. I can suggest using promises.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question