ES6 Promises Example

Change class name on click in jQuery

by Anchit Gupta

HTML

<div id="banner-message">
  <p>ES6 promises Example</p>
</div>

CSS

body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#banner-message {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  font-size: 25px;
  text-align: center;
  transition: all 0.2s;
  margin: 0 auto;
  width: 300px;
}

button {
  background: #0084ff;
  border: none;
  border-radius: 5px;
  padding: 8px 14px;
  font-size: 15px;
  color: #fff;
}

#banner-message.alt {
  background: #0084ff;
  color: #fff;
  margin-top: 40px;
  width: 200px;
}

#banner-message.alt button {
  background: #fff;
  color: #000;
}

JavaScript

const getGamesList = () => {
  return new Promise((resolve, reject) => {
    let request = new XMLHttpRequest();

    request.open('GET', 'https://cors-anywhere.herokuapp.com/http://starlord.hackerearth.com/gamesext');

    request.onload = function(){
      if (request.status == 200){
        resolve(request.response);
      } else{
        reject(Error('there is some error'));
      }
    }

    request.onerror = function () {
      reject(Error('Error fetching data.')); // error occurred, reject the  Promise
    };

    request.send(); //send the request

  })
}

getGamesList().then(function(data){
  console.log('Got data! Promise fulfilled.');
  let parsedData = JSON.parse(data);
/*   console.log(parsedData); */
 /* document.getElementsByTagName('body')[0].textContent = JSON.parse(parsedData[0]).title; */
},function (error) {
    console.log('Promise rejected.');
    console.log(error.message);
});