gpt4 book ai didi

javascript - 如何按照我需要的顺序获取日志消息?

转载 作者:行者123 更新时间:2023-12-03 01:04:08 26 4
gpt4 key购买 nike

如何防止首先记录 Service running ... msg?我想要 testDBConnection fn 中的消息。首先被记录。当数据库未运行时,我希望继续记录看起来数据库未运行消息,一旦数据库启动数据库连接已建立服务正在运行... 消息应遵循。我尝试了多种方法,但无法想出正确的代码。感谢您的帮助。

index.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}`);
});

db.js

import knex from 'knex';
import config from '../config/config';
import logger from '../config/winston';

const { db } = config;
let pool;

const testDBConnection = (client) => {
const intervalId = setInterval(async () => {
try {
await client.select(1);
logger.info('DB connection has been established');
clearInterval(intervalId);
} 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
});
testDBConnection(pool);
}
};

export const getDb = () => pool;

最佳答案

您可以使用 async/await 来实现这一点。

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 内的记录器。另一种方法是只使用 promise then

关于javascript - 如何按照我需要的顺序获取日志消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52487874/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com