Skip to content

Instantly share code, notes, and snippets.

@wjx
Created March 24, 2017 01:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wjx/592d39416361f1e4a3027c055fed92dc to your computer and use it in GitHub Desktop.
Save wjx/592d39416361f1e4a3027c055fed92dc to your computer and use it in GitHub Desktop.
Promise version answer to the EloquentJavascript Exercise 20.1
var http = require("http");
var Promise = require("promise");
function getAuthor(type) {
return new Promise(function(resolve, reject) {
var request = http.request({
hostname: "eloquentjavascript.net",
path: "/author",
method: "GET",
headers: {Accept: type}
}, function(response) {
if (response.statusCode < 200 || response.statusCode >= 300)
return reject(new Error('status code=' + response.statusCode));
var body = [];
response.on('data', function(chunk) {
body.push(chunk);
});
response.on('end', function() {
resolve("Type " + type + ": " + Buffer.concat(body).toString());
});
});
request.end();
});
}
var types = [
"text/plain",
"text/html",
"application/json"
];
types.map(getAuthor).reduce(function(sequence, typePromise) {
return sequence.then(function() {
return typePromise;
}).then(function(body) {
console.log(body);
});
}, Promise.resolve());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment