0
我希望創建一個模塊陣列到require
,循環遍歷需要的模塊,require
他們異步,然後回調。我曾嘗試以下:NodeJS&Electron:異步多個所需文件
// 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
爲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
。因此,callback
可能會失敗。它是否正確?
請注意,這是我的問題的延續:Where/How Should I require multiple modules for performance?