简体   繁体   English

Node.js模块函数返回未定义而不是异步的

[英]Nodejs module function returns undefined, not asynchronous

Pretty (very) new to Node so this is probably stupid. Node非常(非常)陌生,所以这可能很愚蠢。 I have a module that defines various routes that I iterate over to define the app's routes. 我有一个模块,该模块定义了要迭代以定义应用程序路由的各种路由。 This works fine. 这很好。

While setting up the route I want to call a function checkAvailableTranslation in another module language that checks whether a translation of that page exists in another language ( req.locale being the user's favoured language that we are trying to find a match for), and if so return a URL fragment for it. 在设置路线时,我想用另一种模块language调用一个函数checkAvailableTranslation ,以检查该页面的翻译是否以另一种语言存在( req.locale是我们尝试查找其匹配项的用户偏爱的语言),以及是否因此返回一个URL片段。

The strings object is loaded from a json file and contains an item translations that is an array of ISO country codes mapped to URL fragments. strings对象是从json文件加载的,包含一个项目translations ,该项目translations是映射到URL片段的ISO国家/地区代码的数组。

** app.js ** ** app.js **

var routes = require("./config/routing.js")
routes.forEach(function(item) {
    item.routes.forEach(function(route) {
        app.get(route.path, function(req, res) {
            var strings = require(route.strings)
            translations = language.checkAvailableTranslation(req.locale, strings.translations))
            console.log(translations) // undefined?!?!?!?!
            res.render(route.render, {
                layout: route.layout,
                strings: strings
            })
        })
    })
})

** strings.translations ** **字符串。翻译**

[
    { "fr": "/fr" },
    { "ar": "/ar" },
    { "es": "/es" },
    { "pt": "/pt" },
    { "de": "/de" }
]

** language.js ** ** language.js **

module.exports = function() {
    var module = {}

    module.checkAvailableTranslation = function(language, translations) {
        translations.forEach(function(el) {
            if( el[language] ) {
                console.log(el[language]) // this logs a matched language
                return el[language] // this disappears into the ether
            }
        })
    }
    return module
}

So everything generally behaves as expected with translations.forEach iterating successfully and finding matches. 因此,通常情况下,所有行为都与translations.forEach一样,能够成功迭代并找到匹配项。 However it doesn't seem to return the value back to app.js - when I output the function's return I get undefined . 但是,它似乎没有将值返回给app.js -当我输出函数的返回值时,我得到的是undefined

Does the fact that strings is being loaded from a json file make this an asynchronous call, as if it were a database? 从json文件加载strings的事实是否使它成为异步调用,就好像它是数据库一样? If so (and that would need explaining), what should I be doing here to set up a promise to deal with this? 如果是这样(那需要解释),我在这里应该做什么以建立一个承诺来解决这个问题?

You're returning from the forEach callback which is not possible. 您无法通过forEach回调返回。 You need to iterate manually over the array or write the result into a variable in the scope of your checkAvailableTranslation method(but still iterate over all items in translations ). 您需要手动遍历数组,或者将结果写入checkAvailableTranslation方法范围内的变量中(但仍然遍历translations 所有项目)。

Manual "forEach" 手册“ forEach”

module.checkAvailableTranslation = function(language, translations) {
    for (
        var i = 0, translation = translations[i][language];
        i < translations.length;
        i++, translation = translations[i][language]
    ) {
        if (translation)
            return translation;
    }
}

Or using Array.prototype.some 或使用Array.prototype.some

function (language, translations) {
    var res;
    translations.some(function (translation) {
        return !!(res = translation[language]);
    });
    return res;
}

EDIT: Ninja approach : 编辑: 忍者方法

function n(l,t,i){return t[i|0][l]||g(l,t,(i|0)+1)}

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

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