首页 > 解决方案 > return 关键字的行为很奇怪

问题描述

我正在开发一个需要检查 Windows 注册表中的键是否存在的 JS(Electron,Node.js)项目。这是我的代码:

function IsSettedUp() {
regedit.list('HKCU\\SOFTWARE')
    .on('data', function (entry) {
        //Returns Keys
        console.log(entry.data.keys)

        //Checks if "WinXSoft" appears in the entry.data.keys array
        var key = $.inArray("WinXSoft", entry.data.keys)

        console.log(key)

        //Returns false if WinXSoft wasn't found
        if (key == -1) {

            return false
        }
        //Returns true if WinXSoft was found
        else {
            return true
        }
    })

    }
    //Should be true or false according to the WinXSoft key
    var z = IsSettedUp();
    console.log(z)

当我创建密钥并运行代码时,这是输出:

console.log(entry.data.keys)输出Array(42)。(预期)

console.log(key)输出 13(预期)

console.log(z)输出undefined(???,应该是真的)

所以,是的,你们知道我该如何解决这个问题吗?

标签: javascriptnode.jselectron

解决方案


尝试从on函数中返回值

function IsSettedUp() {
     var result = false;
     regedit.list('HKCU\\SOFTWARE').on('data', function (entry) {
        //Returns Keys
        console.log(entry.data.keys)

        //Checks if "WinXSoft" appears in the entry.data.keys array
        var key = $.inArray("WinXSoft", entry.data.keys)

        console.log(key)

        //Returns false if WinXSoft wasn't found
        if (key == -1) {

            result = true;
        }
        //Returns true if WinXSoft was found
        else {
            result = false;
        }
    });
    return result;
 }

推荐阅读