Promise Chaining

 function saveToDB(data) {

  return new Promise((resolve, reject) => {
    let internetSpeed = Math.floor(Math.random() * 10) + 1;
    if (internetSpeed > 4) {
      resolve("Success:Data saved");
    } else {
      reject("failure: weak connection");
    }
  });
}

// saveToDB("Abhiii")
// .then(() => {
//   console.log("data1 saved");
//   saveToDB("helloo").then(() => {
//     console.log("Data2 saved");
//   });
// })
// .catch(() => {
//   console.log("Promise was rejected");
// });

saveToDB("Abhiii")
  .then(() => {
    console.log("data1 saved");
    return saveToDB("hello");
  })
  .then(() => {
    console.log("data2 saved");
    return saveToDB("Hiii");
  })
  .then(() => {
    console.log("Data3 saved");
  })
  .catch(() => {
    console.log("Promise was rejected");
  });




Comments

Popular posts from this blog

Callback Hell

TODO list with DOM

Refactoring callback hell code