Created
October 7, 2021 14:21
-
-
Save dino-/6e2109dc80745014e1daf6ad95f8799b to your computer and use it in GitHub Desktop.
A JavaScript promises cheat-sheet
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
// A JavaScript promises cheat-sheet | |
// an immediately resolved promise | |
const p1 = Promise.resolve('foo'); | |
// can get it after the fact, unlike events | |
p1.then((res) => console.log('p1 got:', res)); | |
// => p1 got: foo | |
const p2 = new Promise((resolve, reject) => { | |
setTimeout(() => resolve(4), 2000); // setTimeout is a "system" call | |
}); | |
// handler can't change promise, just value | |
p2.then((res) => { | |
res += 2; | |
console.log('p2 computed value:', res); | |
}); | |
// => p2 computed value: 6 | |
// still gets 4 | |
p2.then((res) => console.log('p2 immutable value:', res)); | |
// => p2 immutable value: 4 | |
// A promise that throws, rather than explicitly reject | |
const p3 = new Promise((resolve, reject) => { | |
if (true) | |
throw new Error('rejected in the Promise'); | |
// same as reject(new Error('rejected in the Promise')); | |
else | |
resolve(4); | |
}); | |
// trailing .catch() handles rejection | |
p3.then((val) => val + 2) | |
.then((val) => console.log('p3 got:', val)) | |
.catch((err) => console.log('p3 error:', err.message)); | |
// => p3 error: rejected in the Promise | |
// A fulfilled promise | |
const p4 = new Promise((resolve, reject) => { | |
resolve(4); | |
}); | |
// Second .then throws error, .catch() still handles it | |
// as rejection anywhere in the processing chain of promise | |
p4.then((val) => val + 2) | |
.then((val) => { throw new Error('step 2 failed!') }) | |
.then((val) => console.log('p4 got', val)) // this never happens | |
.catch((err) => console.log('p4 error:', err.message)); | |
// => p4 error: step 2 failed! | |
// A Promise that times out after ms milliseconds | |
const delay = (ms) => { | |
return new Promise((resolve, reject) => { | |
setTimeout(resolve, ms); | |
}); | |
} | |
// Whichever Promise fulfills first is the result passed to our handler | |
const p5 = Promise.race( | |
// Could be something that may take time, like a document fetch.. | |
// [ fetchJSON('http://www.api.com/profile/currentuser'), | |
[ Promise.resolve({ user: 'foo' }) // ..but let's just resolve it quickly | |
, delay(5000).then(() => { user: 'bar' }) | |
]) | |
p5.then((json) => { | |
// this will be 'bar' if the above fetch takes longer than 5 sec. | |
console.log("p5 user:", json.user); | |
}) | |
.catch((err) => { | |
console.log("p5 error:", err); | |
}); | |
// => p5 user: foo |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment