Skip to content

Instantly share code, notes, and snippets.

@rajatjain-21
Last active September 8, 2022 03:11
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 rajatjain-21/35928ef65e2ccfe25d8ec8a3a797e004 to your computer and use it in GitHub Desktop.
Save rajatjain-21/35928ef65e2ccfe25d8ec8a3a797e004 to your computer and use it in GitHub Desktop.
Promise example
// -------------------------------------------------------------------
// 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