|
| 1 | +const express = require("express"); |
| 2 | +const app = express(); |
| 3 | + |
| 4 | +const wrapAsync = fn => (req, res, next) => { |
| 5 | + Promise.resolve(fn(req, res, next)).catch(err => next(err)); |
| 6 | +}; |
| 7 | + |
| 8 | +// this function simulates one asynchronous operation, |
| 9 | +// e.g. loading user profile from database |
| 10 | +const loadUserProfileFromDB = userName => { |
| 11 | + return new Promise(resolve => { |
| 12 | + setTimeout(() => resolve({ name: userName, gender: "M" }), 10); |
| 13 | + }); |
| 14 | +}; |
| 15 | + |
| 16 | +const getUserProfile = async (req, res, next) => { |
| 17 | + const userName = req.params.userName; |
| 18 | + const userProfile = await loadUserProfileFromDB(userName); |
| 19 | + res.send(userProfile); |
| 20 | +}; |
| 21 | + |
| 22 | +app.get("/users/:userName", wrapAsync(getUserProfile)); |
| 23 | + |
| 24 | +// this function simulates one asynchronous operation that generate errors, |
| 25 | +// e.g. loading an blog entry from database |
| 26 | +const loadBlogPostFromDB = postId => { |
| 27 | + return new Promise((resolve, reject) => { |
| 28 | + setTimeout(() => reject(new Error("Network Connection Error")), 10); |
| 29 | + }); |
| 30 | +}; |
| 31 | + |
| 32 | +const getBlogPost = async (req, res, next) => { |
| 33 | + const postId = req.params.postId; |
| 34 | + // note: this line below would throw error |
| 35 | + const post = await loadBlogPostFromDB(postId); |
| 36 | + res.return(post); |
| 37 | +}; |
| 38 | + |
| 39 | +app.get("/posts/:postId", wrapAsync(getBlogPost)); |
| 40 | + |
| 41 | +app.use(function(err, req, res, next) { |
| 42 | + res.status(500); |
| 43 | + res.send({ err: err.message }); |
| 44 | +}); |
| 45 | + |
| 46 | +const server = app.listen(3000, function() { |
| 47 | + console.log("Application started...."); |
| 48 | +}); |
0 commit comments