-
Notifications
You must be signed in to change notification settings - Fork 13
/
3_Promisification.js
75 lines (55 loc) · 1.82 KB
/
3_Promisification.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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/* Promisification:
http://bluebirdjs.com/docs/api/promisification.html
Converting an Async Function that uses the Error First Callback function, into a promise */
const Promise = require('bluebird');
const fs = require('fs');
const request = require('needle');
const crypto = require('crypto');
const GitHubHandle = 'FILL_ME_IN';
// (1) Asyncronous HTTP request: Callback
const getGitHubProfile = function (user, callback) {
let url = 'https://api.github.com/users/' + user;
let options = {
headers: { 'User-Agent': 'request' },
};
request.get(url, options, function (err, res, body) {
if (err) {
callback(err, null);
} else if (body.message) {
callback(
new Error('Failed to get GitHub profile: ' + body.message),
null
);
} else {
callback(null, body);
}
});
};
// (1) Asyncronous HTTP request: Promise
const getGitHubProfileAsync = Promise.promisify(getGitHubProfile);
getGitHubProfileAsync(GitHubHandle)
.then(res => console.log(res))
.catch(err => console.log('err')); // cleaner?
// (2) Asyncronous token generation: Callback
const generateRandomToken = function (callback) {
crypto.randomBytes(20, function (err, buffer) {
if (err) { return callback(err, null); }
callback(null, buffer.toString('hex'));
});
};
// (2) Asyncronous token generation: Promise
const generateRandomTokenAsync; // TODO
// (3) Asyncronous file manipulation: Callback
const readFileAndMakeItFunny = function (filePath, callback) {
fs.readFile(filePath, 'utf8', function (err, file) {
if (err) { return callback(err); }
var funnyFile = file.split('\n')
.map(function (line) {
return line + ' lol';
})
.join('\n');
callback(funnyFile);
});
};
// (3) Asyncronous file manipulation: Promise
const readFileAndMakeItFunnyAsync; // TODO