2017-06-13 57 views
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"); 
} 

然而,儘管pathrequire是正確的,我得到的錯誤:

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?

回答

0

至於我還記得你不能要求這樣的(動態/運行時)模塊,只有這樣,我認爲你可以做到這一點是通過手動閱讀在運行時通過fs模塊文件。 有關如何執行此操作的更多詳細信息,請訪問:Loading Node.js modules dynamically based on route