我正在编写一个新的应用程序,其中一个要求是我使用"直接"表达包含bin/www
和app.js
。
为方便起见,我通常只是合并其中两个。现在我不能,我想知道......
如何从app.js
?
以下是完整的app.js.这不起作用,因为只要这一行发生:
var connection = await mysql.createConnectionP({
匿名函数返回一个未解析的promise。所以指定的" app"是不完整的,因为有效设置它的代码还没有运行。
保持app.js / www duo的数据库异步连接的最佳做法是什么?
我可以连接到www
中的数据库,但是我需要以某种方式将数据库值传递回app.js
- 这基本上是唯一的方法吗?
var express = require('express')
var path = require('path')
var favicon = require('serve-favicon')
var logger = require('morgan')
var cookieParser = require('cookie-parser')
var bodyParser = require('body-parser')
var promisify = require('util').promisify
var index = require('./routes/index')
var users = require('./routes/users')
var app = express()
var prpl = require('prpl-server')
var jsonreststores = require('jsonreststores')
var mysql = require('mysql')
mysql.createConnectionP = promisify(mysql.createConnection)
console.log("1")
;(async () => {
var connection = await mysql.createConnectionP({
host: 'localhost',
user: 'root',
password: 'ppp',
database: 'sasit'
})
connection.connectP = promisify(connection.connect)
connection.queryP = promisify(connection.query)
connection.endP = promisify(connection.end)
await connection.connectP()
var res = await connection.queryP('SELECT 1 + 1 AS solution')
console.log('The solution is: ', res[0].solution)
await connection.end()
// view engine setup
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'jade')
// uncomment after placing your favicon in /public
// app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))
app.use(cookieParser())
// app.use(express.static(path.join(__dirname, 'public')));
// app.use('/', index);
// app.use('/users', users);
app.get('/*', prpl.makeHandler('./public/build', {
builds: [
{name: 'es6-unbundled', browserCapabilities: ['es2015', 'push']},
{name: 'es6-bundled', browserCapabilities: ['es2015']},
{name: 'es5-bundled'}
]
}))
// catch 404 and forward to error handler
app.use(function (req, res, next) {
var err = new Error('Not Found')
err.status = 404
next(err)
})
// error handler
app.use(function (err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message
res.locals.error = req.app.get('env') === 'development' ? err : {}
// render the error page
res.status(err.status || 500)
res.render('error')
})
})()
module.exports = app