Skip to content

Instantly share code, notes, and snippets.

@colinmeinke
Last active August 29, 2015 14:25
Show Gist options
  • Save colinmeinke/15a1f927bf562d353fa8 to your computer and use it in GitHub Desktop.
Save colinmeinke/15a1f927bf562d353fa8 to your computer and use it in GitHub Desktop.
Async JS
const getArticles = async () => {
try {
const response = await fetch( 'articles.json' );
const data = await response.json();
data.articles.forEach( article => {
let { author, title } = article;
console.log( `${title} written by ${author}` );
});
} catch ( e ) {
console.error( e );
}
};
getArticles();
var getArticles = function () {
var xhr = new XMLHttpRequest();
xhr.addEventListener( 'load', function ( e ) {
if ( this.status >= 200 && this.status < 300 ) {
var data = JSON.parse( this.responseText );
data.articles.forEach( function ( article ) {
var author = article.author;
var title = article.title;
console.log( title + ' written by ' + author );
});
} else {
console.error( 'Ajax request error' );
}
}, false);
xhr.addEventListener( 'error', function ( e ) {
console.error( 'Ajax request error' );
}, false);
xhr.addEventListener( 'abort', function ( e ) {
console.error( 'Ajax request error' );
}, false);
xhr.open( 'GET', 'articles.json', true );
xhr.send();
}
getArticles();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment