作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我希望使快速路线更加模块化。我对使用 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')
这是有 promise 的。
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
})
})
如何将 promise /路由返回到app.use
?
最佳答案
app.use需要中间件功能。也就是说,一个采用 (req, res, next)
的函数。
总体来说:
app.use(function(req, res, next){
promiseRoute(probably_pass_things_in).nodeify(next);
});
nodeify 是将 promise 转换为 next
将采取的回调。请注意,您可以使用用于 Express 的第三方 Promise 中间件。
关于javascript - 将 promise 的包装快速路由返回到 app.use(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31225249/
到目前为止,我已经生成了以下代码来尝试将相关数据整合在一起。 但是,使用“+ 7”函数会产生以下问题。 Registration date = '2018-01-01' 它正在推迟 2018-04-0
我已经成功地将我的自定义购物车发布到 PayPal——它处理订单非常漂亮,当收到付款时,它会将数据发回我在配置中指定的 URL。代码基于此处找到的库:http://www.phpfour.com/bl
我是一名优秀的程序员,十分优秀!