Node.js 等待一个插件完成注册,然后继续注册下一个插件
我如何等待一个插件完成注册,然后再继续注册下一个插件 我希望使用使用插件Node.js 等待一个插件完成注册,然后继续注册下一个插件,node.js,fastify,Node.js,Fastify,我如何等待一个插件完成注册,然后再继续注册下一个插件 我希望使用使用插件fastfy env从.env文件检索的凭据初始化与数据库的连接 在加载环境变量之前,Fastify继续注册Fastify sequelize-插件。这导致错误TypeError:无法读取未定义的属性“DB\u NAME” 'use strict' const path = require('path') const AutoLoad = require('fastify-autoload') const fastifyE
fastfy env
从.env
文件检索的凭据初始化与数据库的连接
在加载环境变量之前,Fastify继续注册Fastify sequelize
-插件。这导致错误TypeError:无法读取未定义的属性“DB\u NAME”
'use strict'
const path = require('path')
const AutoLoad = require('fastify-autoload')
const fastifyEnv = require('fastify-env')
const fsequelize = require('fastify-sequelize')
module.exports = function (fastify, opts, next) {
fastify
.register(fastifyEnv, {
schema: {
type: 'object',
required: [ 'PORT', 'NODE_ENV', 'DB_NAME', 'DB_USERNAME', 'DB_PASSWORD' ],
properties: {
PORT: { type: 'integer' },
NODE_ENV: { type: 'string' },
DB_NAME: { type: 'string' },
DB_USERNAME: { type: 'string' },
DB_PASSWORD: { type: 'string' }
}
},
dotenv: true
}).ready((err) => {
if (err) console.error(err)
console.log("config ready=",fastify.config) // This works!
})
fastify.register(fsequelize, {
instance: 'sequelize',
autoConnect: true,
dialect: 'postgres',
database: fastify.config.DB_NAME,
username: fastify.config.DB_USERNAME,
password: fastify.config.DB_PASSWORD
})
fastify.register(AutoLoad, {
dir: path.join(__dirname, 'plugins'),
options: Object.assign({}, opts)
})
fastify.register(AutoLoad, {
dir: path.join(__dirname, 'services'),
options: Object.assign({}, opts)
})
next()
}
Fastify以相同的方式同步注册插件和中间件,并按照注册顺序依次注册。它不应该异步要求这些模块 但是,对于每个插件,您可以使用许多不同的前后处理程序
Fastify以相同的方式同步注册插件和中间件,并按照注册顺序依次注册。它不应该异步要求这些模块 但是,对于每个插件,您可以使用许多不同的前后处理程序
您的脚本应该可以运行,我认为问题是由其他原因造成的 无论如何,您可以在
.register
之后使用.after
API:
const Fastify = require('fastify')
const fastify = Fastify({ logger: false })
fastify.register((instance, opts, next) => {
console.log('one')
setTimeout(next, 1000)
}).after(() => {
fastify.register((instance, opts, next) => {
console.log('two')
setTimeout(next, 1000)
})
fastify.register((instance, opts, next) => {
console.log('three')
next()
})
})
fastify.register((instance, opts, next) => {
console.log('four')
next()
})
fastify.listen(3000)
将打印:
一个
两个
三
四
你的脚本应该可以运行,我认为问题是由其他原因引起的 无论如何,您可以在
.register
之后使用.after
API:
const Fastify = require('fastify')
const fastify = Fastify({ logger: false })
fastify.register((instance, opts, next) => {
console.log('one')
setTimeout(next, 1000)
}).after(() => {
fastify.register((instance, opts, next) => {
console.log('two')
setTimeout(next, 1000)
})
fastify.register((instance, opts, next) => {
console.log('three')
next()
})
})
fastify.register((instance, opts, next) => {
console.log('four')
next()
})
fastify.listen(3000)
将打印:
一个
两个
三
四
这不是问题的答案,但最简单的解决方法是将我的凭据放在一个.js文件中,然后需要它。(跳过dotenv或fastifyEnv的使用)这并不是问题的答案,但最简单的解决方法是将我的凭证放在一个.js文件中,并需要它。(跳过dotenv或fastifyEnv的使用)