-
-
Save minmaxdata/53b09b1ca7b9cd9d96c18b88d247fb32 to your computer and use it in GitHub Desktop.
Promises in JavaScript with examples
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* ** Diffrence between Tasks and Promises: | |
* Once settled, a promise can not be resettled. Calling resolve() or reject() again will have no effect. The immutability of a settled promise is an important feature. | |
* https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-promise-27fc71e77261 | |
* *** First arg is for 'resolved' status, and the second is for 'rejected' | |
*/ | |
// exampe 1 | |
const myPromise = function () { | |
return new Promise((Yay, Nay) => { | |
// Uncomment whatever state you want to return, first one to fire is the return. | |
// Yay() | |
Nay() | |
console.log('after message'); | |
}) | |
} | |
myPromise() | |
.then(() => console.log('RESOLVED')) | |
.catch(() => console.log('REJECTED')) | |
// example2 with passed value | |
const myPromise2 = function (n) { | |
return new Promise((Yay, Ops) => { | |
if (n < 10) { | |
Yay('I\'m Resolved') // Passing argument to be used by 'then' | |
} else { | |
Ops('I\'m Rejected') | |
} | |
}) | |
} | |
myPromise2(50) | |
.then(resolveResponse => console.log('RESOLVED:', resolveResponse)) // "RESOLVED: I'm Resilved" | |
.catch(rejectResponse => console.log('REJECTED:', rejectResponse)) // "REJECTED: I'm Rejected" | |
// third one just for fun | |
const myPromise3 = function () { | |
return new Promise((Yay, Nay) => { | |
// Uncomment whatever state you want to return | |
Yay() | |
// Nay() | |
}) | |
} | |
myPromise3() | |
.then(() => console.log('RESOLVED')) | |
.catch(() => console.log('REJECTED')) | |
const myPromise4 = function (n) { | |
return new Promise((Yay, Ops) => { | |
if (n < 10) { | |
Yay('I\'m Resolved4') | |
} else { | |
Ops('I\'m Rejected4') | |
} | |
}) | |
} | |
myPromise4(50) | |
.then(resolveResponse => console.log('RESOLVED:', resolveResponse)) | |
.catch(rejectResponse => console.log('REJECTED:', rejectResponse)) | |
console.log('Even though i\'m at EOF, I appear first because Promises seems to be gone to the next event loop'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment