---
title: "Javascript Scope In Callback"  
description: "Javascript Scope In Callback"  
author: "Anonymous User"  
published: 2013-03-05  
updated: 2013-03-05  
canonical: https://www.mindstick.com/forum/621/javascript-scope-in-callback  
category: "javascript"  
tags: ["javascript"]  
reading_time: 2 minutes  

---

# Javascript Scope In Callback

Hi Mindstickians!

I have a [method](https://www.mindstick.com/forum/166/webservice-method) with a [callback](https://www.mindstick.com/articles/152/using-the-callback) inside of [nodeJS](https://www.mindstick.com/blog/637/create-and-run-a-html-page-in-nodejs-in-windows-os) where I'm trying to set a value in the outer [function](https://www.mindstick.com/articles/13001/multi-statement-table-valued-user-defined-function-in-sql-server) that can be returned with the [result](https://www.mindstick.com/blog/12011/advantages-of-getting-result-oriented-seo-from-an-agency) of the data that is being passed in the callback to a [mongoose](https://www.mindstick.com/forum/161460/what-is-mongoose-and-why-is-it-used-in-mean-applications) call:

'use [strict](https://yourviews.mindstick.com/view/81367/usa-imposes-strict-ban-on-syria)';

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

exports.getAllAlerts = function() {\
var result = [];\
Alert.find({}, function(err, [alerts](https://answers.mindstick.com/qa/102510/what-is-the-purpose-of-google-alerts-for-notifications)) {\
if(err) {\
console.log('[exception](https://www.mindstick.com/articles/1824/objective-c-exception-handling) 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](https://www.mindstick.com/blog/33258/jee-mains-and-jee-advance-exams)

## Replies

### Reply by AVADHESH PATEL

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 );\
});


---

Original Source: https://www.mindstick.com/forum/621/javascript-scope-in-callback

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
