Skip to content

Instantly share code, notes, and snippets.

@jpdevries
Created May 30, 2017 12:42
Show Gist options
  • Save jpdevries/19ea5ae2f0193a7cccbaedfe309544fd to your computer and use it in GitHub Desktop.
Save jpdevries/19ea5ae2f0193a7cccbaedfe309544fd to your computer and use it in GitHub Desktop.
An introduction to JavaScript Promises using a real world analogy
// A husband forges out into the night...
// promising his wife to go to the store and come back with milk
const goToStore = new Promise((res, rej) => {
// do our code
// then when we are done, call res()
// if anything goes wrong, throw an error by calling rej()
const wentToStore = Math.random() <= .75; // 75% chance he remembers to go to the store
if(wentToStore) {
res('[Husband arrives at store]');
} else {
rej(new Error("Wife: You didn't go to the store???!!!"));
}
});
const buyMilk = new Promise((res, rej) => {
const rememberMilk = Math.random() <= .35; // 35% chance he remembers the milk
if(rememberMilk) {
res("Wife: You remembered the milk!")
} else {
rej(new Error("Wife: You forgot the milk again?!"));
}
});
Promise.all([
goToStore,
buyMilk
]).then((messages) => {
// all the promises fullfilled, we get an Array of what each resolved
console.log(messages);
}).catch((err) => {
console.log('(something went wrong)');
console.error(err);
});
@joeldbirch
Copy link

Very good example, thanks. But can you explain why "Husband arrives at store" is wrapped in an array, please? The other message isn't, so this is the only unclear thing to me.

@joeldbirch
Copy link

Whoops, I see the square brackets are part of the string now!

@jpdevries
Copy link
Author

@joeldbirch I've actually had a few people confused by the brackets, they are meant to be from the perspective "narrator"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment