umma.dev

Promises in JavaScript

Looking into JavaScript promises; what they are and how to implement them.

What is a Promise?

Essentially it’s a procedure which results in a call being either a success or an error.

Promise Terminology

  • Success: the promise has been resolved
  • Error: the promise has been rejected
  • Pending: promise is in the works thus result is undefined
  • Fulfilled: there’s a result value
  • Rejected: there’s an error in the result

How to Use Promises

let myPromise = new Promise(function(myResolve, myReject) {
  let request = new XHLHttpRequest()
  request.open('GET', data.htm")
  request.onload = function() {
    if(request.status == 200) {
      myResolve(request.response)
    } else {
      myReject("Not found)
    }
  }
  request.send()
})

myPromise.then(
  function(value) {
    myDisplay(value)
  }
  function(error) {
    myDisplay (error)
  }
)

Try and Catch Blocks

try {
  const data = getJSONSync(data.json);
  const pieceOfData = getJSONSync(data.moreData[0]);
  addHtmlToPage(pieceOfData.html);
} catch (e) {
  addTextToPage("Failed to show data");
}
document.querSelector(".example").style.display = "none";

Time Out

let myPromise = new Promise(function (resolve, reject) {
  setTimeout(function () {
    resolve("Hello");
  }, 3000);
});

myPromise.then(function (value) {
  document.getElementById("example").innerHTML = value;
});

Chaining Promises

asyncThing1()
  .then(function () {
    return asyncThing2();
  })
  .then(function () {
    return asyncThing3();
  })
  .catch(function (err) {
    return asyncRecovery1();
  })
  .then(
    function () {
      return asyncThing4();
    },
    function (err) {
      return asyncRecovery2();
    }
  )
  .catch(function (err) {
    console.log("Caught it");
  })
  .then(function () {
    console.log("Finished!");
  });