Skip to content

Instantly share code, notes, and snippets.

@vi-kas
Last active July 9, 2019 09:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vi-kas/5fb2449695324b1a967257530f2bf1e4 to your computer and use it in GitHub Desktop.
Save vi-kas/5fb2449695324b1a967257530f2bf1e4 to your computer and use it in GitHub Desktop.
Simple JavaScript Promises
/*
Promise Flow in JS - https://mdn.mozillademos.org/files/15911/promises.png
1. Creating a Promise by passing an executor
2. Using Promise prototype methods
2a. then handler
2b. catch handler
2c. finally handler
3. Using Promise static methods
3a. Promise.resolve
3b. Promise.reject
3c. Promise.all
3d. Promise.race
Running:-
Open https://playcode.io/367625?tabs=script.js,preview,console
Paste Code and Run.
*/
//------------------------------------------------
// [1.] Creating a Promise by passing an executor
const kept = true;
/*
Creates a new Promise, which takes an executor function. This function has two parameters - resolve and reject.
These two params are also functions. For positive cases, return the resolve, reject otherwise.
*/
const promise1 = new Promise(/* executor */ function(resolve, reject){
if(kept){
resolve("This is resolved.")
} else {
reject("This is rejected.")
}
});
// The promise1 doesn't perform anything which takes time, hence you'll see a resolved promise logged with this.
console.log(promise1);
// Creates another Promise, this one resolved after 10 seconds.
const promise2 = new Promise(function(resolve, reject){
setTimeout(function(){
resolve({
message: "Validation failed for foo.",
code: "121211"
});
}, 10 * 1000);
});
/*
At first it should give:-
Promise {<pending>}
- [[PromisStatus]] "pending"
- [[PromisValue]] undefined
----------- After 10 seconds -----------
At first it should give:-
Promise {<resolved>} ...
- [[PromisStatus]] "resolved"
- [[PromisValue]] Object
"code": ...
"message" ...
*/
console.log(promise2);
//------------------------------------------------
/*
2. Using Promise prototype methods
2a. then handler
2b. catch handler
2c. finally handler
A promise can have multiple handlers!
*/
const deepWorkPromise = new Promise(function(resolve, reject){
var deepWorkHoursPromised = 9;
var deepWorkHoursAchieved = 10;
if(deepWorkHoursAchieved > deepWorkHoursPromised){
resolve({
message: "Deep Work Hours Achieved.",
workHours: deepWorkHoursAchieved
});
} else {
reject("I couldn't achieve my goal this week.");
}
});
// Here then is working on onFulfilled handler. [see below]
deepWorkPromise.then(function(value){
console.log("I am on track!", JSON.stringify(value));
console.log("Work hours achieved: ", value.workHours);
});
// Here catch is working on onRejected handler
deepWorkPromise.catch(function(reason){
console.log("Don't worry! Try harder next week!");
});
// Here then is working on onFulfilled & onRejected handler.
deepWorkPromise.then(function(value){
console.log("I am on track!", JSON.stringify(value));
}, function(reason){
console.log("Anyway If I keep track of my work, I will achieve it!");
});
deepWorkPromise.finally(function(){
console.log("Anyway If I keep track of my work, I will achieve it!");
});
//------------------------------------------------
/*
3. Using Promise static methods
3a. Promise.resolve
3b. Promise.reject
3c. Promise.all
3d. Promise.race
*/
//Promise.resolve
const resolvedPromise = Promise.resolve("Good Work!");
resolvedPromise.then(function(value){
console.log("Promise Resolved.", value);
});
//Promise.reject
const rejectedPromise = Promise.reject("Not Acceptable!");
rejectedPromise.catch(function(reason){
console.log("Promise Rejected.", reason);
});
/*
Promise.all(iterable)
As per MDN Documentation:
Promise.all(iterable) returns single Promise that resolves when all promises in iterable argument have resolved
or when the iterable argument contains no promises. It rejects with the reason of the first promise that rejects.
*/
const promise3 = new Promise(function(resolve, reject){
setTimeout(function(){
resolve("After 3 seconds!");
}, 3 * 1000);
});
const promise4 = new Promise(function(resolve, reject){
setTimeout(function(){
resolve("After 4 seconds!");
}, 4 * 1000);
});
//Promise.all(iterable)
const allPromises = Promise.all([promise3, promise4]);
allPromises.then(function(value){
console.log("Hurrah! all Promises Resolved.");
});
allPromises.catch(function(reason){
console.log("Huh! At least one Promise Rejected.");
});
/*
Promise.race
As per MDN Documentation:
Promise.race(iterable) method returns a promise that resolves or rejects as soon as one of the promises
in the iterable resolves or rejects, with the value or reason from that promise.
*/
//Promise.race(iterable)
const racePromises = Promise.race([promise3, promise4]);
racePromises.then(function(value){
console.log("Hurrah! This Promise Resolved First!", value);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment