Skip to content

Instantly share code, notes, and snippets.

@ryasmi
Last active February 23, 2018 15:44
Show Gist options
  • Save ryasmi/57cc42cbd70afcb461982fca684bb773 to your computer and use it in GitHub Desktop.
Save ryasmi/57cc42cbd70afcb461982fca684bb773 to your computer and use it in GitHub Desktop.
JS Mushroom Episode 2 - Promises (2018-02-23)
// Using resolved promises with the .then callback.
Promise.resolve('hello world').then((message) => {
console.log(message); // Logs "hello world" in the console.
});
// Using rejected promises with the .catch callback.
Promise.reject('error message').catch((err) => {
console.error(err); // Logs "error message" in the console.
});
// Using resolved promises with async await inside an IIFE (Immediately Invoked Function Expression).
(async () => {
const message = await Promise.resolve('hello world');
console.log(message); // Logs "hello world" in the console.
})();
// Using rejected promises with async await.
(async () => {
try {
await Promise.reject('error message');
} catch (err) {
console.error(err); // Logs "error message" in the console.
}
})();
// Making your own resolved promises
const resolvingPromise = () => {
return new Promise((resolve, reject) => {
resolve('hello world');
});
};
// Making your own rejected promise.
const rejectingPromise = () => {
return new Promise((resolve, reject) => {
reject('error message');
});
};
// Waiting for many resolved promises with Promise.all
(async () => {
const promise1 = Promise.resolve('hello world 1');
const promise2 = Promise.resolve('hello world 2');
const promises = [promise1, promise2];
const messages = await Promise.all(promises);
const message1 = messages[0];
const message2 = messages[1];
console.log(message1); // Logs "hello world 1" in the console.
console.log(message2); // Logs "hello world 2" in the console.
})();
// Handling a rejected promise with Promise.all
(async () => {
try {
const promise1 = Promise.reject('error message 1');
const promise2 = Promise.reject('error message 2');
const promises = [promise1, promise2];
await Promise.all(promises);
} catch (err) {
console.error(err); // Logs "error message 1" in the console.
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment