Skip to content

Instantly share code, notes, and snippets.

@aashish-chaubey
Created August 20, 2019 20:25
Show Gist options
  • Save aashish-chaubey/17542f5a74bcd17dd927fe1b0b987f50 to your computer and use it in GitHub Desktop.
Save aashish-chaubey/17542f5a74bcd17dd927fe1b0b987f50 to your computer and use it in GitHub Desktop.
Implementing and using the basic promise
/**
* @author Aashish Chaubey
* @link https://github.com/aashish-chaubey
*/
/**
* First Create a Promise my implementing it with a `new` keyword
* Do all the heavy weight operations in the promise
* Store the promise in a variable
*/
let myPromise = new Promise((resolve, reject) => {
setTimeout(() => {
let rand = Math.random()
console.log(rand)
if(rand < 0.5) {
resolve("The Random Value is less than 0.5")
} else {
reject("Random Value is greater then 0.5")
}
}, 2000)
})
/**
* Execute the promise
* Call the `.then()` and `.catch()` for the resolve and rejected values respectively
*/
myPromise
.then(resp => {
console.log(resp);
})
.catch(err => {
console.log(err);
})
@aashish-chaubey
Copy link
Author

Important to note is that:

Callback saves us from callback hell in chaining and thus making the code more readable

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