Skip to content

Instantly share code, notes, and snippets.

@wjx wjx/get_authors.js
Created Mar 24, 2017

Embed
What would you like to do?
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
You can’t perform that action at this time.