Flama
Flama

Reputation: 868

Get result from function applied to API in another .js

I wanted to do something as simple as this (let's assume I want the first element). The function getRooms is defined in another .js

 $(document).ready(function() {
   $("#title").text(api.rooms.getRooms()[0]); //DOESNT WORK
 });

I have another file called api.js which has the following:

var api = class {
    static get baseUrl() {
    return "http://127.0.0.1:8080/api/";
  }

  static get timeout() {
    return 60 * 1000;
  }
}

api.rooms = class {
  static get url() {
    return api.baseUrl + "rooms/";
  }

  static getRooms() {
       return $.ajax({
            url: api.room.url,
            method: "GET",
            dataType: "json",
            timeout: api.timeout
             .then(function(data) {
                 data.rooms.map(item => item.name);
               })

          }); 
    }
}

How can I get the information/array return by getRooms() in my other .js file?

Upvotes: 1

Views: 40

Answers (1)

Andrew
Andrew

Reputation: 1621

It is not working because in getRooms(), the then() function is used which returns a jQuery promise (read about jQuery promises to get an understanding of why this is needed). Basically, since the $.ajax call is asynchronous, it can't simply return the result of an operation right away. So the promise is used to achieve this. Your code should look something like this instead:

$(document).ready(function() {
    $("#title").text(api.rooms.getRooms().done(function(data) {
        console.log(JSON.stringify(data));
    }).fail(function(jqXHR, textStatus, errorThrown) {
        console.log("Request failed: jqXHR.status=" + jqXHR.status + ", textStatus=" + textStatus + ", errorThrown=" + errorThrown);
    });
});

Upvotes: 1

Related Questions