how to handle promise code example

Example 1: javascript promise

var promise = new Promise(function(resolve, reject) {
  // do some long running async thing…
  
  if (/* everything turned out fine */) {
    resolve("Stuff worked!");
  }
  else {
    reject(Error("It broke"));
  }
});

//usage
promise.then(
  function(result) { /* handle a successful result */ },
  function(error) { /* handle an error */ }
);

Example 2: promise catch

//create a Promise
var p1 = new Promise(function(resolve, reject) {
  resolve("Success");
});

//Execute the body of the promise which call resolve
//So it execute then, inside then there's a throw
//that get capture by catch
p1.then(function(value) {
  console.log(value); // "Success!"
  throw "oh, no!";
}).catch(function(e) {
  console.log(e); // "oh, no!"
});

Example 3: 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 4: return new Promise(res => {

// the execution: catch -> then
new Promise((resolve, reject) => {

  throw new Error("Whoops!");

}).catch(function(error) {

  alert("The error is handled, continue normally");

}).then(() => alert("Next successful handler runs"));