Skip to content

Instantly share code, notes, and snippets.

@wjx
Created December 12, 2016 16:11
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/9133981e1670293cae26d90199693b07 to your computer and use it in GitHub Desktop.
Save wjx/9133981e1670293cae26d90199693b07 to your computer and use it in GitHub Desktop.
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