-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathasync_await_example.js
More file actions
55 lines (44 loc) · 1.51 KB
/
Copy pathasync_await_example.js
File metadata and controls
55 lines (44 loc) · 1.51 KB
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
44
45
46
47
48
49
50
51
52
53
54
55
const express = require("express");
const app = express();
const PORT = 3000;
const wrapAsync = fn => (req, res, next) => {
Promise.resolve(fn(req, res, next)).catch(err => next(err));
};
const notAsync = (req, res) => {
res.send("i am not async function");
};
app.get("/notAsync", wrapAsync(notAsync));
// this function simulates one asynchronous operation,
// e.g. loading user profile from database
const loadUserProfileFromDB = userName => {
return new Promise(resolve => {
setTimeout(() => resolve({ name: userName, gender: "M" }), 10);
});
};
const getUserProfile = async (req, res, next) => {
const userName = req.params.userName;
const userProfile = await loadUserProfileFromDB(userName);
res.send(userProfile);
};
app.get("/users/:userName", wrapAsync(getUserProfile));
// this function simulates one asynchronous operation that generate errors,
// e.g. loading a blog entry from database
const loadBlogPostFromDB = postId => {
return new Promise((resolve, reject) => {
setTimeout(() => reject(new Error("Network Connection Error")), 10);
});
};
const getBlogPost = async (req, res, next) => {
const postId = req.params.postId;
// note: this line below would throw error
const post = await loadBlogPostFromDB(postId);
res.send(post);
};
app.get("/posts/:postId", wrapAsync(getBlogPost));
app.use(function(err, req, res, next) {
res.status(500);
res.send({ err: err.message });
});
const server = app.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
});