Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

commented May 31, 2017

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

This comment has been minimized.

Copy link

commented May 31, 2017

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

@jpdevries

This comment has been minimized.

Copy link
Owner Author

commented Jul 26, 2017

@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
You can’t perform that action at this time.