简体   繁体   English

回调中的Javascript范围

[英]Javascript Scope In Callback

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: 我有一个在nodeJS内部具有回调的方法,在该方法中,我试图在外部函数中设置一个值,该值可以与在回调中传递给猫鼬调用的数据结果一起返回:

'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? 如何使用猫鼬回调中返回的警报值设置result []的值?

Thanks in advance 提前致谢

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. find()最有可能异步运行,在这种情况下,您将始终返回一个空Array ,因为在返回值时,该值未定义也未分配。

You would need to rewrite your .getAllAlerts() method so it allows a callback function for itself, like 您需要重写.getAllAlerts()方法,以便它允许自己使用回调函数,例如

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM