OneCompiler

promices

123

Example heading with h2 size

Example heading with h3 size

Following is sample java code.


// function printString(string){
//   setTimeout(
//     () => {
//       console.log(string)
//     },
//     Math.floor(Math.random() * 100) + 1
//   )
// }
 
// function printAll(){

//   printString("A")
//   printString("B")
//   printString("C")

// }
// printAll()

async function printString(string) {
  return new Promise(resolve => {
    setTimeout(() => {
      console.log(string);
      resolve(); 
    }, Math.floor(Math.random() * 100) + 1);
  });
}

 async function printAll() {
   await printString("A");
   await printString("B");
  await  printString("C");
}

printAll(); 


const promise1 = new Promise((resolve, reject) => {
  setTimeout(resolve, 290, "race 1");
}); //will be resolved after 290

const promise2 = 93; //non-promise
const promise4 = new Promise((resolve, reject) => {
  setTimeout(reject, 300, "race2");
});

const promise3 = new Promise((resolve, reject) => {
  setTimeout(resolve, 100, "resolved2");
}); // will be resolved after 100ms


//play here with  Promise.all, race, any
Promise.all([promise1, promise2, promise4, promise3])
  .then((values) => {
    console.log(values);
  })
  .catch((err) => {
    console.log(err);
  });
  
  const addition = (a, b) =>
  new Promise((resolve, reject) => {
    if (typeof a == "number" && typeof b == "number") {
      //reject('a + b');
      throw Error('asdas')
    } else {
      reject("Not a Number");
    }
  });

addition(10, 5)
  .then((response) => {
    console.log(response);
  })
  .catch((err) => {
    console.log(err);
  })
  .finally(() => {
    console.log("Numbers are added");
  });