Handling Rejections

 let h1 = document.querySelector("h1");

function changeColor(color, delay) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      let num = Math.floor(Math.random() * 10) + 1;
      if (num < 3) {
        reject("Promise is rejected");
      }
      h1.style.color = color;
      resolve("color changed");
    }, delay);
  });
}
async function demo() {
  await changeColor("red", 1000);
  await changeColor("blue", 1000);
  await changeColor("green", 1000);
  await changeColor("yellow", 1000);

  let a = 5;
  console.log(a);
  console.log("new Number:", a + 3);
}
console.log(demo());



HANDLING REJECTIONS

let h1 = document.querySelector("h1");
function changeColor(color, delay) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      let num = Math.floor(Math.random() * 10) + 1;
      if (num < 3) {
        reject("Promise is rejected");
      }
      h1.style.color = color;
      console.log(`color changed to ${color}!`);
      resolve("color changed ");
    }, delay);
  });
}
async function demo() {
  try {
    await changeColor("red", 1000);
    await changeColor("blue", 1000);
    await changeColor("green", 1000);
    await changeColor("yellow", 1000);
  } catch (err) {
    console.log("eroor:", err);
  }

  let a = 5;
  console.log(a);
  console.log("new Number:", a + 3);
}
console.log(demo());





Comments

Popular posts from this blog

Callback Hell

TODO list with DOM

Refactoring callback hell code