Javascript Scope In Callback

Total Post:70

Points:494

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

      Modified On Mar-29-2018 11:09:04 PM

Answer

Please check, If you want to make this post sponsored

You are not a Sponsored Member. Click Here to Subscribe the Membership.