Classes with async call and Promise

by Sascha

HTML

<div id="result">

</div>

CSS

#result {
  background: white;
  color: black;
}

JavaScript

/**
Callback example with asynchronous method call.
*/

var ServiceHandler = function() {
  var self = this;

  self.loadData = function() {
    document.getElementById("result").append("LoadData() called. ");
    return new Promise(function(resolve, reject) {
      setTimeout(function() {
        resolve("Fertig");
      }, 4000);

    });

  }
}

PageController = new function() {
  var self = this;
  var _serviceHandler = new ServiceHandler();

  _resumeOperation = function() {
    document.getElementById("result").append("ResumeOperation() called. ");
  }

  _init = function() {
    document.getElementById("result").append("Init() called. ");
    _serviceHandler.loadData(_resumeOperation).then(function(v) {
        document.getElementById("result").append(v);
      })
      .catch(function(v) {
        document.getElementById("result").append("Ein Fehler ist aufgetreten: " + v);
      });
  }
  _init();
}