I'm trying to call a function once after all ajax calls are done. The $.when
below is being called too soon with an empty array of promises. searchRecommendations()
is being called several times from the success of a few previous $.ajax
calls. Could that be responsible somehow?
var MAX = 2; //Maximum levels queried
var ARTISTS = []; //Multidimensional array with the number of potential 'artists' i.e. compare Madonna, to Beethoven to Eminem to nth-artist
var RELEVENT_ARTISTS = 2; //Number of relevent artists added to the list for each new artist
var promises = [];
$(function(){
init(0);
})
function init(i){
for(var i; i<1; i++){
console.log('searchArtists for relevant artist '+$('input')[i].value)
var artist = $('input')[i].value;
$.ajax({
url: 'https://api.spotify.com/v1/search',
data: {
q: artist,
type: 'artist'
},
success: function (response) {
console.log(response.artists.href);
searchRecommendations(response.artists.items[0].id, 0)
//nextLevel(0)
}
});
}
//console.log(ARTISTS)
//getMatches(ARTISTS)
}
function searchRecommendations(artist, depth) {
console.log(' ')
console.log('searchRecommendations '+artist+ ' '+ depth )
if(depth == MAX){ return console.log('max reached '+depth) } else {
promises.push(
$.ajax({
url: 'https://api.spotify.com/v1/artists/' + artist + '/related-artists',
data: {
type: 'artist',
},
success: function (response) {
console.log('RESPONSE');
console.log(response)
for(var r=0; r<RELEVENT_ARTISTS; r++){
console.log(response.artists[r].name)
var obj = { 'artist' : response.artists[r].name, 'level':(depth+1)*5 }
ARTISTS.push(obj)
searchRecommendations(response.artists[r].id, depth+1) //Recursion
}
}
})
)
}
}
$.when.apply(undefined, promises).done(function() {
convert_artists_to_nodes_and_links(ARTISTS)
console.log( 'this is being called too soon')
console.log( promises )
})