Promise example
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
// ------------------------------------------------------------------- | |
// this function simulates a request that needs to run async | |
// ------------------------------------------------------------------- | |
function favoriteBlogger(favorite) { | |
return new Promise((resolve, reject) => { | |
if (favorite === 'rajatexplains') { | |
resolve(favorite); | |
} else { | |
reject('your preference is poor😛'); | |
} | |
}); | |
} | |
// ------------------------------------------------------------------- | |
// this is the code that actually loads data | |
// ------------------------------------------------------------------- | |
// 🚫 this doesn’t work | |
function getFavoriteBloggerBroken() { | |
// the return value is a Promise, not the value that resolved the Promise | |
const blogger = favoriteBlogger('rajatexplains'); | |
// that means we can’t return the value from this function 😱 | |
console.log(`My favorite blogger is a ${blogger}.`); | |
//=> My favorite blogger is a [object Promise]. | |
} | |
// ✅ this works | |
function getFavoriteBlogger() { | |
const blogger = favoriteBlogger('rajatexplains'); | |
// we can only get to the value using the `.then` chain | |
blogger.then((value) => { | |
console.log(`My favorite blogger is a ${value}.`); | |
//=> My favorite blogger is a rajatexplains. | |
}); | |
} | |
getFavoriteBlogger(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment