【问题标题】:NodeJS & Electron: Async Multiple Required FilesNode JS 和 Electron:异步多个必需文件
【发布时间】:2017-11-15 16:24:43
【问题描述】:

我希望创建一个模块数组到require,以异步方式遍历模块以要求require,然后回调。我尝试了以下方法:

// async require module for other required modules
function asyncRequire (requireList, callback) {
    if (!Array.isArray(requireList)) {return};

    var index = -1;
    var loop = {}
    loop.next = function () {
        if (index < requireList.length) {
            var asyncOperation = function (j) {
                setTimeout(function() {
                    index++;
                    var item = requireList[index];
                    console.log(item);
                    window[item] = require(item);
                    loop.next();
                }, 10);
            }
            asyncOperation(requireList);
        } else {
            if (typeof callback === "function") {
                setTimeout(function() {
                    callback();
                }, 1000);
            }
        }
    }
    loop.next();
}

// usage example
var requireList = ['moduleName', 'moduleName2']

asyncRequire(requireList, callback)

function callback() {
    console.log("success");
}

但是,虽然requirepath 是正确的,但我得到了错误:

AssertionError
actual: undefined
expected: true
generatedMessage: false
message: "missing path"
name: "AssertionError"
operator:"=="
stack:"AssertionError: missing path↵    at Module.require (module.js:496:3)↵    at require (internal/module.js:20:19)↵    at asyncRequire.js:18:21"
__proto__: Error

我也觉得完成requirecallback之间可能会有延迟。因此,callback 可能会失败。这是正确的吗?

请注意这是我的问题的延续:Where/How Should I require multiple modules for performance?

【问题讨论】:

    标签: javascript node.js electron


    【解决方案1】:

    据我所知,您不能要求这样的模块(动态/运行时),我认为您可以做到这一点的唯一方法是在运行时通过 fs 模块手动读取文件。 有关如何执行此操作的更多详细信息,请点击此处:Loading Node.js modules dynamically based on route

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-14
      • 2013-10-03
      • 1970-01-01
      • 2017-02-03
      • 2018-09-20
      • 2015-08-04
      • 2019-01-12
      • 1970-01-01
      相关资源
      最近更新 更多