Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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

Maxim Melnic
Maxim Melnic
4,178 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