forked from vefforritun/vef2-2021
-
Notifications
You must be signed in to change notification settings - Fork 0
/
10.async-await.js
43 lines (34 loc) · 1.04 KB
/
10.async-await.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import { readFile } from 'fs/promises';
import express from 'express';
const app = express();
async function read(req, res) {
let data = '';
try {
data = await readFile('./10.async-await.js');
} catch (e) {
console.error('error', e);
return res.status(500).send('Villa');
}
// Ef við köstum þessari villu og pössum ekki upp á að grípa mun
// forritið okkar krassa. Á við um allar villur utan try catch í
// async middleware!
// throw new Error('boo');
return res.type('txt').send(data);
}
/**
* Wrap an async function with error handling
* @params {function} fn Function to wrap
* @returns {Promise} Promise with error handling
*/
function catchErrors(fn) {
return (req, res, next) => fn(req, res, next).catch(next);
}
// Grípum villur og erum örugg
app.get('/', catchErrors(read));
// Ónei! Villur munu krassa forritinu okkar
app.get('/unsafe', read);
const hostname = '127.0.0.1';
const port = 3000;
app.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});