1
0
Fork 0

Video 97: Integrating Async/Await

This commit is contained in:
JayWll 2020-02-23 17:07:26 -07:00
parent cd08113b6e
commit c2e488633a
1 changed files with 32 additions and 24 deletions

View File

@ -8,68 +8,76 @@ const port = process.env.PORT || 4200
app.use(express.json()) app.use(express.json())
app.post('/users', (req, res) => { app.post('/users', async (req, res) => {
const user = new User(req.body) const user = new User(req.body)
user.save().then(() => { try {
await user.save()
res.status(201).send(user) res.status(201).send(user)
}).catch((e) => { } catch (e) {
res.status(400).send(e) res.status(400).send(e)
}) }
}) })
app.get('/users', (req, res) => { app.get('/users', async (req, res) => {
User.find({}).then((users) => { try {
const users = await User.find({})
res.send(users) res.send(users)
}).catch((e) => { } catch (e) {
res.status(500).send() res.status(500).send()
}) }
}) })
app.get('/users/:id', (req, res) => { app.get('/users/:id', async (req, res) => {
const _id = req.params.id const _id = req.params.id
User.findById(_id).then((user) => { try {
const user = await User.findById(_id)
if (!user) { if (!user) {
return res.status(404).send() return res.status(404).send()
} }
res.send(user) res.send(user)
}).catch((e) => { } catch (e) {
res.status(500).send() res.status(500).send()
}) }
}) })
app.post('/tasks', (req, res) => { app.post('/tasks', async (req, res) => {
const task = new Task(req.body) const task = new Task(req.body)
task.save().then(() => { try {
await task.save()
res.status(201).send(task) res.status(201).send(task)
}).catch((e) => { } catch (e) {
res.status(400).send(e) res.status(400).send(e)
}) }
}) })
app.get('/tasks', (req, res) => { app.get('/tasks', async (req, res) => {
Task.find({}).then((tasks) => { try {
const tasks = await Task.find({})
res.send(tasks) res.send(tasks)
}).catch((e) => { } catch (e) {
res.status(500).send() res.status(500).send()
}) }
}) })
app.get('/tasks/:id', (req, res) => { app.get('/tasks/:id', async (req, res) => {
const _id = req.params.id const _id = req.params.id
Task.findById(_id).then((task) => { try {
const task = await Task.findById(_id)
if (!task) { if (!task) {
return res.status(404).send() return res.status(404).send()
} }
res.send(task) res.send(task)
}).catch((e) => { } catch (e) {
res.status(500).send() res.status(500).send()
}) }
}) })
app.listen(port, () => { app.listen(port, () => {