KillerPollo
KillerPollo

Reputation: 113

How to get multiple ajax request with promises

I'm trying to get a single image from each ajax request and append it to a li box container, the first ajax returns a list of 20 objects, with name and a url

$.ajax({
  url: "http://pokeapi.co/api/v2/pokemon/",
  dataType: "json",
  method: "GET",
  cache: false,
  success: function(data) {
    for (var i = 0; i<data.results.length ;i++){
      $("#root ul").append('<li class="box"></li>');
      $("li").eq(i).append('<h2>' + data.results[i].name +'</h2>');
    }
    setPkmImage(data.results);
    console.log(data);
  },
  error: function(data) {
    console.log("Error");
  }

});

The problem starts when I try to make a call for each of those objects to request an image, it works with the async: false, but i don't want to do it that way since it takes a lot of time to load all the images.

function setPkmImage(res){
  for (var i = 0; i < res.length; i++) {

    var promise = $.ajax({
      url: res[i].url,
      dataType: "json",
      method: "GET",
      cache: false,
      //async: false,
      promise.done( function(data) {
        console.log(data);
        $("#root ul");
        $("li").eq(i).append('<img src="' + data.sprites.front_default+ '"/>');

      });
      promise.fail( function(data) {
        console.log("Error");
      });

    });
   }
  }

I'm trying to use promises but I don't know exactly how to structure it

Upvotes: 1

Views: 1732

Answers (2)

charlietfl
charlietfl

Reputation: 171679

Two major problems, one is syntax and the other is you need a closure loop

First the $.ajax is not closed properly.

Should look more like:

 var promise = $.ajax({
      url: res[i].url,
      dataType: "json",
      method: "GET",
      cache: false
 });

 promise.done(...
 promise.fail(...

As for the closure loop, i won't be what you want it to be inside the ajax callbacks because the for loop will have been completed before the data for requests is returned. Thus i will be at it's maximum by then

Try changing the for loop to $.each which creates a closure

$.each(res, function(i, item){

       var promise = $.ajax({
          url: item.url,
          dataType: "json",
          method: "GET",
          cache: false
     });

     promise.done(...
     promise.fail(...

})

Upvotes: 1

Andrey Ravkov
Andrey Ravkov

Reputation: 1484

I usually use the next solution. After first request is done, I've insert to dom img with url (url is come from request) and browser will load images automatically.

Upvotes: 0

Related Questions