forked from basicallydan/q-examples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
request-with-processing.js
43 lines (36 loc) · 1015 Bytes
/
request-with-processing.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
var Q = require('q');
var request = require('request');
var getData = function () {
var d = Q.defer();
request({ url : 'http://hndroidapi.appspot.com/news/format/json/page/1?appid=QExamples&callback=', json : true }, function (err, response, body) {
if (err) {
var error = new Error('Something went wrong trying to get HN Articles');
error.innerError = err;
throw error;
}
d.resolve(body);
});
return d.promise;
};
var countPoints = function (data) {
var d = Q.defer();
var i = 0;
var numPoints = 0;
for ( ; i < data.items.length; i++) {
if (data.items[i].score) {
numPoints += +(data.items[i].score.split(' ')[0]);
}
}
d.resolve(numPoints);
return d.promise;
};
var outputResults = function (numberOfPoints) {
var d = Q.defer();
console.log('There are currently a total of ' + numberOfPoints + ' points on the Hacker News Frontpage');
};
getData()
.then(countPoints)
.then(outputResults)
.fail(function (error) {
console.log('Something went wrong: ' + error.message);
});