Skip to content

Instantly share code, notes, and snippets.

@rbaumbach
Last active August 18, 2018 23:10
Show Gist options
  • Save rbaumbach/0464d0a6862b99bf212912ddc8e6954e to your computer and use it in GitHub Desktop.
Save rbaumbach/0464d0a6862b99bf212912ddc8e6954e to your computer and use it in GitHub Desktop.
Having "fun" with YavaScript objects
// Creating ALF object
const alf = {
name: 'Gordon Shumway',
'home-planet': 'Melmac',
likes: ['cats', 'jokes', 'mischief'],
eatCat: function() {
return new Promise(function(resolve, reject) {
const isAbleToCatchCat = Math.floor(Math.random() * 2);
setTimeout(function() {
if (isAbleToCatchCat) {
resolve('Cat was eaten');
} else {
reject('Cat got away');
}
}, 1000);
});
}
}
console.log(alf);
console.log(alf['home-planet']);
console.log(alf.likes[1]);
/*
Output:
{ name: 'Gordon Shumway',
'home-planet': 'Melmac',
likes: [ 'cats', 'jokes', 'mischief' ],
eatCat: [Function: eatCat] }
Melmac
jokes
*/
// Having ALF attempt to eat a cat
// Using promises
alf.eatCat().then(function(resolve) {
console.log(resolve);
console.log('Alf ate, but could eat again');
}).catch(function(reject) {
console.log(reject);
console.log('Alf is still hungry');
});
/*
Cat got eaten Output:
Cat was lunch
Alf ate, but could eat again
Cat got away Output:
Cat got away
Alf is still hungry
*/
// Using async/await
const eatAlf = async function() {
try {
result = await alf.eatCat()
console.log(result);
console.log('Alf is crazy');
} catch (error) {
console.log(error);
}
console.log('I wonder what the cat population is like on Melmac')
}
eatAlf();
/*
Cat got eaten Output:
Cat was lunch
Alf is crazy
I wonder what the cat population is like on Melmac
Cat got away Output:
Cat got away
I wonder what the cat population is like on Melmac
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment