Autocomplete with nested ajax calls

Autocomplete with nested ajax calls

I am currently working on implementing an album search autocomplete using the Spotify Metadata API. I have most of the features complete, but I am having trouble when doing a nested call to retrieve the album cover art. Here I believe is the root of my problem. When I do the ajax call to retrieve the image it does work, and I get the right data, but the return statement is not getting executed. What I am trying to do is get the first four results, for each get an image and return the label, item and image. Thanks in advanced. I appreciate your help!

  1. function getAutocompleteResults(url) {
  2.       var d = new $.Deferred();
  3.       $.get(url, function(data) {
  4.           d.resolve(data);
  5.       });
  6.       return d;
  7.     }

  8.     function getCoverArtForResults(url) {
  9.       var d = new $.Deferred();
  10.       $.ajax({
  11.           url: url,
  12.           dataType: "jsonp",
  13.           success: function (image) {
  14.             d.resolve(image);
  15.           }
  16.       });
  17.       return d;
  18.     }

  19.     $('#spotify-album-search').autocomplete({
  20.       source:
  21.         function (query, process) {
  22.           $.when(
  23.               getAutocompleteResults('http://ws.spotify.com/search/1/album.json?q=' + query.term)
  24.           ).then(function (data) {
  25.             process($.map(data.albums.slice(0, 4), function(item) {
  26.               $.when (
  27.                 getCoverArtForResults('https://embed.spotify.com/oembed/?url=' + item.href)
  28.               ).then(function (image) {
  29.                 return { label: item.artists[0].name + ' - ' + item.name, album: item, image: image.thumbnail_url };
  30.               });
  31.             }));
  32.           });
  33.       },
  34.       select: function (e, ui) {
  35.         console.log("selected= " + ui.item.album);
  36.       },
  37.       messages: {
  38.         noResults: '',
  39.         results: function() {}
  40.       }
  41.     })
  42.     .data('ui-autocomplete')._renderItem = function(ul, item) {
  43.       return $('<li>')
  44.           .data( "ui-autocomplete-item", item)
  45.           .append('<a>' + item.label + '<img src="' + item.image + '" alt="" />' + '</a>')
  46.           .appendTo(ul);
  47.     };