服务器Node.js启动时,我捕获了错误
(节点:2320)UnhandledPromiseRejectionWarning:TypeError:无法读取 未定义的属性“同步”
在app.js中
const specs = require('./swagger')
const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
const morgan = require('morgan')
const config = require('../config/config')
const swaggerUi = require('swagger-ui-express')
const app = express()
app.use(morgan('combined'))
app.use(bodyParser.json())
app.use(cors())
app.use('/api-docs',swaggerUi.serve,swaggerUi.setup(specs.default))
require('./passport')
require('./routes')(app)
async function fn () {
const { sequelize } = await require('./models')
await sequelize.sync({ force: false })
.then(() => {
app.listen(config.development.port)
console.log(`Server started on port ${config.development.port}`)
})
}
// call fn
fn().then(module.exports = app)
我在文件夹“ ./models”中具有要序列化的属性的文件
const path = require('path')
const Sequelize = require('sequelize')
const config = require('../../config/config')
const db = {}
const sequelize = new Sequelize(
config.development.database,config.development.username,config.development.password,{
dialect: config.development.dialect,host: config.development.host
}
)
const klaw = require('klaw')
const through2 = require('through2')
const excludeDirFilter = through2.obj(function (item,enc,next) {
if (!item.stats.isDirectory()) this.push(item)
next()
})
async function fn () {
await klaw(__dirname)
.pipe(excludeDirFilter)
.on('data',item => {
if (path.basename(item.path) !== 'index.js') {
const model = sequelize.import(item.path)
db[model.name] = model
}
})
.on('end',() => {
console.log(1)
})
await Object.keys(db).forEach(function (modelName) {
if ('associate' in db[modelName]) {
db[modelName].associate(db)
console.log(2)
}
})
db.sequelize = sequelize
db.Sequelize = Sequelize
}
// call fn
fn().then(module.exports = db)
故事的开始是我需要获取模型的文件夹和子文件夹中所有文件的列表,为此,我使用了npm -i klaw。但是后来,据我了解,递归搜索的执行时间开始花费更多时间,因此我尝试使用异步/等待。从而导致当前错误。我的主题是新的,很难理解。预先谢谢你