Debian Codegraph @

deferred/examples/gather-paginated-search-results.js

raw
1 "use strict";
2
3 // Let's say we're after content that is paginated over many pages on some
4 // website (like search results). We don't know how many pages it spans.
5 // We only know by reading page n whether page n + 1 exists.
6
7 // 1. Define simple download function, it downloads page at given path from
8 // predefinied domain and returns promise:
9
10 var deferred = require("deferred")
11 , http = require("http");
12
13 var getPage, pageN, result = {};
14
15 getPage = function (path) {
16 var d = deferred();
17
18 http.get({ host: "www.example.com", path: path }, function (res) {
19 res.setEncoding("utf-8");
20 var content = "";
21 res.on("data", function (data) { content += data; });
22 res.on("end", function () { d.resolve(content); });
23 }).on("error", d.reject);
24
25 return d.promise;
26 };
27
28 // 2. Invoke promise loop
29
30 pageN = 1;
31 getPage("/page/" + pageN)(function processContent(content) {
32 var isNextPage = false;
33 // ...populate result...
34
35 // ...decide whether we need to download next page
36
37 if (isNextPage) return getPage("/page/" + ++pageN)(processContent);
38 return result;
39 }).done(function (finalResult) {
40 // Process final result
41 });