how a promise works code example
Example 1: javascript create promise
// base case
const promise = new Promise(executor);
// more complex example
const coinflip = (bet) => new Promise((resolve, reject) => {
const hasWon = Math.random() > 0.5 ? true : false;
if (hasWon) {
setTimeout(() => {
resolve(bet * 2);
}, 2000);
} else {
reject(new Error("You lost...")); // same as -> throw new Error ("You lost ...");
}
});
Example 2: what is a promise
// Promise is a special type of object that helps you work with asynchronous operations.
// Many functions will return a promise to you in situations where the value cannot be retrieved immediately.
const userCount = getUserCount();
console.log(userCount); // Promise {<pending>}
// In this case, getUserCount is the function that returns a Promise. If we try to immediately display the value of the userCount variable, we get something like Promise {<pending>}.
// This will happen because there is no data yet and we need to wait for it.