2017-06-13 7 views
0

モジュールの配列をrequireに作成し、必要なモジュールをループし、非同期でrequireをコールバックし、コールバックしたいとします。私は以下試みた:NodeJS&Electron:Async Multiple Required Files

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

しかし、requireためpathが正しいが、私はエラーを取得:

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もrequireの完了との間に遅延があるかもしれないと感じを、およびcallback。したがって、callbackが失敗する可能性があります。これは正しいです?

これは私の質問の続きですご注意:Where/How Should I require multiple modules for performance?

答えて

0

は限り私は、あなたがこのようなモジュール(動的/ランタイム)が必要とすることはできません覚えているとして、私はあなたがこれを行うことができると思う唯一の方法は、手動で読み込むことです実行時にfsモジュールを介してファイル。 詳細については、こちらをご覧ください。Loading Node.js modules dynamically based on route