JavaScript AJAX Basics (retiring) jQuery and AJAX Stage 3 Challenge

Maxim Melnic
Maxim Melnic
4,177 Points

My solution using Promise!

Maybe someone will be useful;)

$(document).ready(function () {
  function ajaxProm (url) {
    return new Promise (function(resolve, reject) {
      $.getJSON(url, function (response) {
        resolve(response);
        }).fail(jqXHR => reject(jqXHR.status));
      });
  };
  let empl = ajaxProm("../data/employees.json");
    empl
    .then(response => genList(response))
    .then(data => genHtmlList(data))
    .then(html => add(html, "#employeeList"))
    .catch(e => alert(e + " " + e.statusText));

  let rooma = ajaxProm("../data/rooms.json");
    rooma
    .then(response => genElist(response))
    .then(data => genEulist(data))
    .then(html => add(html, "#roomList"))
    .catch(e => alert(e + " " + e.statusText));
});

//Helper functions

function genElist (response) {
  let list = "";
    $.each(response, function (index, value) {
    if (value.available) {
      list += "<li class = 'empty'>";
    } else {
      list += "<li class = 'full'>";
    }
      list += value.room + "</li>";
  });
   return list;
};

function genEulist (data) {
  return '<ul class="rooms">' + data + '</ul>';
};

function genHtmlList (data) {
  return '<ul class="bulleted">' + data + '</ul>';
};

function genList (response) {
    let list = "";
    $.each(response, function (index, value) {
    if (value.inoffice) {
      list += "<li class = 'in'>";
    } else {
      list += "<li class = 'out'>";
    }
      list += value.name + "</li>";
  });
   return list;
};

function add (data, div) {
  $(div).html(data);
};

1 Answer