Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

JavaScript Promise Examples

To demonstrate the use of promises, we will revisit the callback examples from the previous chapter:

  • Waiting for a Timeout
  • Waiting for a File

Waiting for a Timeout

Example Using Callback

setTimeout(function() { myFunction(“I love You !!!”); }, 3000);

function myFunction(value) {
  document.getElementById(“demo”).innerHTML = value;
}

Example Using Promise

let myPromise = new Promise(function(myResolve, myReject) {
  setTimeout(function() { myResolve(“I love You !!”); }, 3000);
});

myPromise.then(function(value) {
  document.getElementById(“demo”).innerHTML = value;
});

Waiting for a file

Example using Callback

function getFile(myCallback) {
  let req = new XMLHttpRequest();
  req.open(‘GET’“mycar.html”);
  req.onload = function() {
    if (req.status == 200) {
      myCallback(req.responseText);
    } else {
      myCallback(“Error: “ + req.status);
    }
  }
  req.send();
}

getFile(myDisplayer);

Example using Promise

let myPromise = new Promise(function(myResolve, myReject) {
  let req = new XMLHttpRequest();
  req.open(‘GET’“mycar.html”);
  req.onload = function() {
    if (req.status == 200) {
      myResolve(req.response);
    else {
      myReject(“File not Found”);
    }
  };
  req.send();
});

myPromise.then(
  function(value) {myDisplayer(value);},
  function(error) {myDisplayer(error);}
);

Browser Support

ECMAScript 2015 (ES6) introduced the JavaScript Promise object.

The following table shows the first browser version to fully support Promise objects:

js 21