Skip to content

Instantly share code, notes, and snippets.

@MrBenJ
Created January 27, 2020 15:58
Show Gist options
  • Save MrBenJ/ba5bc1bd7e80cd0640a8f027799456a0 to your computer and use it in GitHub Desktop.
Save MrBenJ/ba5bc1bd7e80cd0640a8f027799456a0 to your computer and use it in GitHub Desktop.
Promise Example
// Required on in a Node.js environment
const fetch = require('isomorphic-fetch');
async function getInfoFromServer() {
// WITHOUT ASYNC/AWAIT
// fetch('https://deckofcardsapi.com/api/deck/new/draw/?count=1')
// .then(response => {
// return response.json();
// }).then(json => {
// console.log('I drew the card, the ' + json.cards[0].value + ' of ' + json.cards[0].suit );
// });
// WITH ASYNC/AWAIT
const response = await fetch('https://deckofcardsapi.com/api/deck/ne/draw/?count=1');
const json = await response.json();
console.log('I drew the card, the ' + json.cards[0].value + ' of ' + json.cards[0].suit);
}
function init() {
getInfoFromServer().then(() => {
console.log('I am finished');
}).catch( (error) => {
console.log('Oh no! Something bad happened');
console.error(error);
});
}
init();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment