Skip to content

Instantly share code, notes, and snippets.

@basecss
Created July 10, 2014 10:31
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 basecss/f47a5de819fed2f24ccb to your computer and use it in GitHub Desktop.
Save basecss/f47a5de819fed2f24ccb to your computer and use it in GitHub Desktop.
JavaScript Promise
function fetchJSON(url) {
	return new Promise(function(resolve, reject) {
		var xhr = new XMLHttpRequest();
		xhr.open('GET', url);
		xhr.responseType = 'json';
		xhr.send();
		xhr.onload = function() {
			if(xhr.response) {
				resolve(xhr.response);
			}
			reject('JSON Error');
		};
		xhr.onloadend = function() {
			reject('Network Error');
		}
	});
}
function showResult(response) {
	console.log(response);
}
function handleError(response) {
	console.log(response);
}
var url = 'http://www.basecss.net/lab/all.json';
fetchJSON(url).then(showResult, handleError);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment