我希望为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");
}
但是,虽然path
的{{1}}是正确的,但我收到错误:
require
我也觉得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
和require
完成之间可能会有延迟。因此,callback
可能会失败。这是对的吗?
请注意,这是我的问题的延续:Where/How Should I require multiple modules for performance?
答案 0 :(得分:0)
据我所知,你不能要求这样的模块(动态/运行时),只有我认为你能做到这一点的方法是在运行时通过public function __construct()
{
// Call the Model constructor
parent::__construct();
$this->load->database();
$this->load->model('user_model'); //database inserter
//Add this library
$this->load->library('form_validation');
}
模块手动读取文件。
有关如何执行此操作的详细信息,请访问:Loading Node.js modules dynamically based on route