Ajax and promises

function getJSON(url) { return new Promise(function(resolve, reject) { var xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.onreadystatechange = handleResponse; xhr.onerror = function(error) { reject(error); }; xhr.send(); function handleResponse() { if(this.readyState === this.DONE) if(this.status === 200) { resolve(JSON.parse(this.responseText)); } else { reject(this.statusText); } } }); } getJSON('data.json').then(doStuff) .then(doMoreStuff) .catch(function(e){ console.log('oups' + e); });

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.