Home > DeveloperSection > Forums > Javascript Scope In Callback
Simons Hood
Simons Hood

Total Post:70

Points:494
Posted on    March-05-2013 3:24 AM

 JavaScript JavaScript 
Ratings:


 1 Reply(s)
 1270  View(s)
Rate this:

Hi Mindstickians!

I have a method with a callback inside of nodeJS where I'm trying to set a value in the outer function that can be returned with the result of the data that is being passed in the callback to a mongoose call:

'use strict';

var mongoose = require('mongoose')
    ,Alert = mongoose.model('Alert');

exports.getAllAlerts = function() {
    var result = [];
    Alert.find({}, function(err, alerts) {
        if(err) {
            console.log('exception while fetching alerts');
        }
        if(alerts) {
            result = alerts;
            console.log('result: ' + result);
        }
    });
    return result;
}
How can I set the value of result[] with the value of alerts that's coming back in the mongoose callback?

Thanks in advance



AVADHESH PATEL

Total Post:604

Points:4228
Posted on    March-05-2013 8:07 AM

Hi Samual!

Most likely, find() runs asyncronously, in that case, you will always return an empty Array, because at the time you return the value, its not defined nor assigned.

You would need to rewrite your .getAllAlerts() method so it allows a callback function for itself, like

exports.getAllAlerts = function( cb ) {
    Alert.find({}, function(err, alerts) {
        if(err) {
            console.log('exception while fetching alerts');
        }

        if(alerts) {
            if( typeof cb === 'function' ) {
                cb( alert || [ ] );
            }
        }
    });
}
...and you would use that in a way like

YourModule.getAllAlerts(function( alerts ) {
    console.log( alerts );
});


Don't want to miss updates? Please click the below button!

Follow MindStick