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!
- function getAutocompleteResults(url) {
- var d = new $.Deferred();
- $.get(url, function(data) {
- d.resolve(data);
- });
- return d;
- }
- function getCoverArtForResults(url) {
- var d = new $.Deferred();
- $.ajax({
- url: url,
- dataType: "jsonp",
- success: function (image) {
- d.resolve(image);
- }
- });
- return d;
- }
- $('#spotify-album-search').autocomplete({
- source:
- function (query, process) {
- $.when(
- getAutocompleteResults('http://ws.spotify.com/search/1/album.json?q=' + query.term)
- ).then(function (data) {
- process($.map(data.albums.slice(0, 4), function(item) {
- $.when (
- getCoverArtForResults('https://embed.spotify.com/oembed/?url=' + item.href)
- ).then(function (image) {
- return { label: item.artists[0].name + ' - ' + item.name, album: item, image: image.thumbnail_url };
- });
- }));
- });
- },
- select: function (e, ui) {
- console.log("selected= " + ui.item.album);
- },
- messages: {
- noResults: '',
- results: function() {}
- }
- })
- .data('ui-autocomplete')._renderItem = function(ul, item) {
- return $('<li>')
- .data( "ui-autocomplete-item", item)
- .append('<a>' + item.label + '<img src="' + item.image + '" alt="" />' + '</a>')
- .appendTo(ul);
- };