M
M
Maxim Nikitin2014-12-23 17:01:40
JavaScript
Maxim Nikitin, 2014-12-23 17:01:40

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);
        })
    },

This method is used in another file to get a collection (example conditional)
getAllProducts: function() {
        var collection;
        productRepository.getProducts(function(error, result) {
            collection = result;
        });
        return collection;
    }

Of course, collection is out of scope in the callback function, so return collection returns undefined.
What can you suggest me?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
vsvladimir, 2014-12-23
@MaxSter

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);
        });        
    }

It is possible asynchronously through promise. Perhaps it is possible and synchronously (did not check) - to wait before the return collection for the execution of the callback - but this will slow down the program at that moment.

H
haiku, 2014-12-23
@haiku

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.

T
trueClearThinker, 2014-12-23
@trueClearThinker

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 question

Ask a Question

731 491 924 answers to any question