如何防止abstract class RateMembershipType(...) : MembershipType(...), IRateOption
object GOLD: RateMembershipType(...)
object BRONZE: MembershipType(...)
fun membershipSelected(membershipSelected: List<RateMembershipType>) = ...
消息首先被记录?我想要Service running ...
fn中的消息。而是先登录。当数据库未运行时,我希望testDBConnection
消息保持记录状态,一旦数据库启动Looks like DB is not running
,DB connection has been established
消息就会跟随。我尝试了多种方法,但是无法提供正确的代码。感谢您的帮助。
index.js
Service running ...
db.js
import app from './config/express';
import config from './config/config';
import logger from './config/winston';
import { initDbConnection } from './server/db';
app.listen(config.port, () => {
initDbConnection();
logger.info(`Service running and listening on port ${config.port}`);
});
答案 0 :(得分:1)
您可以为此使用异步/等待。
import app from './config/express';
import config from './config/config';
import logger from './config/winston';
import { initDbConnection } from './server/db';
app.listen(config.port, async () => {
await initDbConnection();
logger.info(`Service running and listening on port ${config.port}`);
});
db.js:
import knex from 'knex';
import config from '../config/config';
import logger from '../config/winston';
const { db } = config;
let pool, connected;
const testDBConnection = (client) => {
return new Promise(resolve => {
const intervalId = setInterval(async () => {
try {
await client.select(1);
if (connected) {
return;
}
connected = true;
logger.info('DB connection has been established');
clearInterval(intervalId);
resolve('success');
} catch (error) {
logger.error('Looks like DB is not running');
}
}, 2000);
});
};
export const initDbConnection = (mock) => {
if (mock) {
pool = knex({});
} else {
pool = knex({
client: 'pg',
version: '7.4.2',
connection: db,
debug: true
});
return testDBConnection(pool);
}
};
export const getDb = () => pool;
这样,在解析initDbConnection之前,不会调用app.listen cb中的记录器。另一种方法是仅使用承诺then
。