节点JS电子:异步多个必需的文件 [英] NodeJS & Electron: Async Multiple Required Files

查看:123
本文介绍了节点JS电子:异步多个必需的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望创建一个模块数组,以要求,循环遍历需要的模块,要求异步,然后回调。我已经尝试过以下操作:

I wish to create an array of modules to require, to loop through the modules to require, require them asynchronously, and then callback. I have tried the below:

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

但是,尽管路径 for require 是正确的,我得到了错误:

However, although the path for require is correct, I get the error:

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

我还认为,完成要求回调。因此,回调可能会失败。这是正确的吗?

I also feel that there may be a delay between the completion of the require, and the callback. Therefore, the callback could fail. Is this correct?

请注意,这是我的问题的延续:我在哪里/如何需要多个模块来提高性能?

Please note this is a continuation of my question: Where/How Should I require multiple modules for performance?

推荐答案

据我所知,您不需要这样的模块(动态/运行时),我认为您可以执行此操作的唯一方法是通过 fs 手动读取文件运行期间的模块。
有关如何执行此操作的更多详细信息,请参见:正在加载节点.js模块基于路由动态

As far as i can remember you cannot require modules like this (dynamically/runtime) , only way i think you can do this is by manually reading the files via fs module during runtime. More details on how to do this is here : Loading Node.js modules dynamically based on route

这篇关于节点JS电子:异步多个必需的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆