replaced some more promises with async/await

This commit is contained in:
Daniel Sommer 2022-02-24 10:41:50 +01:00
parent ad111f7709
commit d4b776333f
3 changed files with 29 additions and 28 deletions

View file

@ -15,17 +15,17 @@ handleInterrupts();
main();
// main - let's get this party started
function main() {
util.fileExists(global.config)
.then((result) => {
global.config = require(result.path);
global.config.path = result.path;
})
.then(logger.initialize)
.then(server.start)
.then(logger.info)
.then(server.handleRequests)
.catch(exit);
async function main() {
try {
const config = await util.fileExists(global.config);
global.config = require(config.path);
global.config.path = config.path;
logger.initialize();
logger.info(await server.start());
server.handleRequests();
} catch (err) {
exit(err);
}
}
// ... and it all comes crashing down
@ -38,9 +38,9 @@ function exit(err, code) {
}
if (err) {
logger.error(err);
logger.error(packageJSON.name + " ended due to an error");
logger.error(packageJSON.name + ' ended due to an error');
} else {
logger.info(packageJSON.name + " shutting down gracefully")
logger.info(packageJSON.name + ' shutting down gracefully')
}
process.exit(code);
}

View file

@ -14,14 +14,11 @@ let loglevel = getLogLevel();
let timestamp = getTimestamp();
function initialize() {
return new Promise((resolve, reject) => {
if (global.config === undefined) {
reject('could not initialize logger, config is undefined');
throw new Error('could not initialize logger, config is undefined');
}
loglevel = getLogLevel();
timestamp = getTimestamp();
resolve();
});
}
// get the loglevel
@ -104,7 +101,11 @@ function error(message) {
}
return;
}
if (message.message) {
trace(message.message, 'error');
return
}
trace(message, 'error');
}
// default logging function

View file

@ -23,19 +23,19 @@ const MODE_POWEROFF = require('./blinkstick.js').MODE_POWEROFF;
const html = require('./index.js').get();
// run the express http server and handle gets/posts
function start() {
return new Promise(function (resolve, reject) {
async function start() {
return await new Promise(function (resolve, reject) {
app.listen(config.server.port, config.server.listen)
.on('listening', function () {
return resolve('server listening on ' + config.server.listen + ':' + config.server.port + '...')
resolve('server listening on ' + config.server.listen + ':' + config.server.port + '...')
})
.on('error', function (err) {
return reject('error starting server (' + err + ')');
reject('error starting server (' + err + ')');
});
});
}
async function handleRequests() {
function handleRequests() {
// GET html page
app.get('*', (request, response) => {
logger.http(request);
@ -121,7 +121,7 @@ async function handleRequests() {
})
.catch((err) => {
response.status(500);
response.end({status: 'error', error: err});
response.end(JSON.stringify({status: 'error', error: err.message}));
});
});
}