【问题标题】:Problems with express middleware priorities快速中间件优先级的问题
【发布时间】:2016-01-20 19:14:30
【问题描述】:

好的,我现在遇到的问题是我的错误处理程序在我当前使用的函数完成之前被调用:

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 阻止所有在它之前加载的页面)

【问题讨论】:

    标签: node.js express routes http-status-code-404 fs


    【解决方案1】:

    将该函数调用移动到回调函数内部的某处:

    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 所有中间件,因为对 require 的调用是同步和阻塞的。

    【讨论】:

    • 没有直接回答我的问题,但确实帮我解决了回调函数的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-24
    • 2021-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多