JAVASCRIPT SCOPE IN CALLBACK

Simons Hood

Total Post:70

Points:494
Posted by  Simons Hood
 1580  View(s)
Ratings:
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

  1. AVADHESH PATEL

    Post:604

    Points:4228
    Re: Javascript Scope In Callback

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

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!