2015-10-21 47 views
0

好吧那我现在有是我的错误处理程序被调用之前一个功能齐全的问题,目前我使用:与快递中间件的优先问题

function loadRoutes(route_path) { 
    fs.readdir(route_path, function(err, files) { 
     files.forEach(function (file) { 
      var filepath = route_path + '/' + file; 
      fs.stat(filepath, function (err, stat) { 
       if (stat.isDirectory()) { 
        loadRoutes(filepath); 
       } else { 
        console.info('Loading route: ' + file); 
        require(filepath)(app); 
       } 
      }); 
     }); 
    }); 
} 

setTimeout(function() { 
    require('./errorhandle'); 
}, 10); 

超时解决方案的工作,但它不是一个适当。如果路线加载时间超过10毫秒,则会再次中断。 (404阻挡在它之前加载所有页面)

回答

0

移动回调函数内部的函数调用的地方:

fs.readdir(route_path, function(err, files) { 
    ... 
    // Move the function call to somewhere inside this callback, 
    ... 
    fs.stat(filepath, function (err, stat) { 
    ... 
    // Or inside this callback, 
    ... 
    }); 
    ... 
    // Or even later inside the first callback. 
    ... 
}) 

我不能告诉什么时候你试图调用功能,但它应该在回调函数中的某个地方调用。您需要确定何时需要调用它。这将在适当的时候执行该函数,而不像setTimeout(),这不意味着以这种方式使用。

另外,您应该在应用程序的开始部分需要所有中间件,因为对require的调用是同步和阻塞的。

+0

没有直接回答我的问题,但确实帮助我解决了回调函数的问题。 – Community