【问题标题】:Returning a promised wrapped express route to app.use()将承诺的包装快递路线返回给 app.use()
【发布时间】:2015-09-22 09:12:58
【问题描述】:

我希望让快速路线更加模块化。我对使用 Promise 读取文件然后返回路由很感兴趣。

代码如下:

var express = require('express')
var router = express.Router()
var app = express()

var Promise = require("bluebird")
var fs = Promise.promisifyAll(require("fs"))

function promiseRoute(file){
  return fs.readFileAsync(file, "utf8")
  .then(JSON.parse)
  .then(function(file){
    if(!file.url) throw new Error("missing url")
    router.get(file.url, function(req, res, next){
      return res.redirect("/hello")
    })
    return router
  })
}

app.use(promiseRoute("../file.json"))

var server = app.listen(3000, function () {})

也试过了

promiseRoute(path.join(__dirname, "./file.json")).then(app.use)

我得到了这个错误。

throw new TypeError('app.use() requires middleware functions')

还有这个承诺。

Unhandled rejection TypeError: Cannot read property 'lazyrouter' of undefined
    at use (/project/node_modules/express/lib/application.js:213:7)
    at tryCatcher (/project/node_modules/bluebird/js/main/util.js:24:31)
    at Promise._settlePromiseFromHandler (/project/node_modules/bluebird/js/main/promise.js:489:31)
    at Promise._settlePromiseAt (/project/node_modules/bluebird/js/main/promise.js:565:18)
    at Promise._settlePromises (/project/node_modules/bluebird/js/main/promise.js:681:14)
    at Async._drainQueue (/project/node_modules/bluebird/js/main/async.js:123:16)
    at Async._drainQueues (/project/node_modules/bluebird/js/main/async.js:133:10)
    at Immediate.Async.drainQueues [as _onImmediate] (/project/node_modules/bluebird/js/main/async.js:15:14)
    at processImmediate [as _immediateCallback] (timers.js:371:17)

也试过这个:

promiseRoute(path.join(__dirname, "./file.json")).then(function(router){
  app.use(function(req, res, next){
    return router
  })
})

如何将承诺/路由返回到app.use

【问题讨论】:

    标签: javascript express promise bluebird


    【解决方案1】:

    这成功了:

    promiseRoute(path.join(__dirname, "./file.json")).then(function(router){
      app.use(router)
    })
    

    【讨论】:

      【解决方案2】:

      app.use 需要中间件功能。也就是一个接受(req, res, next) 的函数。

      总的来说:

      app.use(function(req, res, next){
           promiseRoute(probably_pass_things_in).nodeify(next);
      });
      

      nodeify 是将 Promise 转换为回调 next 将采取。请注意,您可以使用第三方承诺中间件进行快递。

      【讨论】:

      • 嘿本杰明!谢谢!我正在尝试在文件中添加一条路线并将其传递给app.use,就像expressjs.com/4x/api.html#router 一样,我无法在该承诺中返回route
      • app.use 接受router 对象或匿名function(req, res, next) 我认为我不能在function(req, res, next) 中返回router 对象,它正在挂起服务器。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-06-10
      • 1970-01-01
      • 2018-10-11
      • 2016-06-15
      • 2018-08-09
      • 1970-01-01
      • 2019-05-25
      相关资源
      最近更新 更多