how to properly use promise 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: making promises in js
getData()
.then(data => console.log(data))
.catch(error => console.log(error));