将承诺的包装快递路线返回给app.use() [英] Returning a promised wrapped express route to app.use()

查看:91
本文介绍了将承诺的包装快递路线返回给app.use()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻求使快速路线更具模块化的方式.我对使用诺言读取文件然后返回路由感兴趣.

I'm looking to make an express route more modular. I was interested in using a promise to read a file then return the route.

代码如下:

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?

How can I return promise / route to app.use?

推荐答案

app.use需要中间件功能.即,采用(req, res, next)的函数.

app.use requires middleware function. That is, a function that takes (req, res, next).

总的来说:

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

nodeify是将诺言转换为next将要执行的回调.请注意,您可以使用第三方承诺中间件来表达.

The nodeify is to convert a promise to a callback next will take. Note there is third party promise middleware for express you can use.

这篇关于将承诺的包装快递路线返回给app.use()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆