Created
December 12, 2016 16:11
-
-
Save wjx/9133981e1670293cae26d90199693b07 to your computer and use it in GitHub Desktop.
Promise version of EloquentJavaScript Excercise 17.1
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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