-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathcallback-hell.js
More file actions
48 lines (44 loc) · 1.6 KB
/
callback-hell.js
File metadata and controls
48 lines (44 loc) · 1.6 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
/**
* Some example of non-functional code to illustrate callback hell.
*/
/*
This is a small, likely snippet of code which pulls recent posts
from a web service API, opens a connection to a database of
some kind, queries for the users who made the posts, and sends
these users in the http response. This is made to illustrate how
quickly simple functionalty can devolve into 'callback hell'.
*/
var db = require('somedatabaseprovider');
http.get('/recentposts', function(req, res) { //get recent posts
db.openConnection('host', creds, function(err, conn) { // open database connection
res.param['posts'].forEach(post) {
conn.query('select * from users where id=' + post['user'], function(err, results) {
conn.close();
res.send(results[0]);
});
}
});
});
/*
This is the same thing as the example above, except I've added gratuitous
exception handling. The effects of callback hell are exacerbated by the
needs fo real, production code.
*/
// what if we add exception handling?
var db = require('somedatabaseprovider');
try {
http.get('/recentposts', function(req, res) { //get recent posts
try {
db.openConnection('host', creds, function(err, conn) { // open database connection
res.param['posts'].forEach(post) {
try {
conn.query('select * from users where id=' + post['user'], function(err, results) {
conn.close();
res.send(results[0]);
});
} catch(e) {/* handle exception */}
}
});
} catch(e) {/* handle exception */}
});
} catch(e) {/* handle exception */}