Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Promise version of EloquentJavaScript Excercise 17.1
//Ref:
//https://developers.google.com/web/fundamentals/getting-started/primers/promises
function requestAuthor(type) {
return new Promise(function(resolve, reject) {
var req = new XMLHttpRequest();
req.open("GET", "http://eloquentjavascript.net/author", true);
req.setRequestHeader("accept", type);
req.onload = function() {
if(req.status == 200) {
resolve(req.responseText);
} else {
reject(Error(req.statusText));
}
};
req.onerror = function() {
reject(Error("Network Error"));
};
req.send(null);
});
}
var types = ["text/plain",
"text/html",
"application/json",
"application/rainbows+unicorns"];
types.map(requestAuthor).reduce(function(sequence, typePromise, i) {
return sequence.then(function() {
return typePromise;
}).then(function(content) {
console.log(types[i] + ":\n", content, "\n");
});
}, 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.