Monday, 15 April 2013

javascript - How to make a callback for my loop function -



javascript - How to make a callback for my loop function -

i have json file keeps urls. made $.each() loop go through json file , soundcloud function on each iteration of loop. in order same result of loop have create callback after each iteration soundcloud function. here tried:

$.getjson("http://www.json-generator.com/api/json/get/bljohiysay?indent=2", function(data){ //link of playlist $.each(data.playlistarray, function(key, val){ //navigate array called playlistarray var songlink = val.url; // value of url in array }, function(){// callback function sc.get('/resolve', { url: songlink }, function(track) { $("#demo").append("<p id= "+ track.id + ">" + track.title + "</p>"); }); }); });

howevere callback not work , not show gathered info sc.get() function of soundcloud. thought create working? or how can have deferred method create chain of functions ??

demo: http://jsfiddle.net/fq2rw/5/

what you're doing here passing 3rd parameter each expecting two. unless i'm missing exact goal, code below should work expected.

sc.initialize({ client_id: "b8f06bbb8e4e9e201f9e6e46001c3acb", }); $.getjson("http://www.json-generator.com/api/json/get/bljohiysay?indent=2", function(data){ //link of playlist $.each(data.playlistarray, function(key, val){ //navigate array called playlistarray var songlink = val.url; // value of url in array sc.get('/resolve', { url: songlink }, function(track) { $("#demo").append("<p id= "+ track.id + ">" + track.title + "</p>"); }); }); });

edit: understand want results in order defined data.playlistarray result set. think need buffer results , process them when answers have been received. code below not optimal may give new ideas.

there's is, of course, no way command in order different 'sc.get()' respond and, consequently, in order 'function(track)' callbacks called. waiting each reply before making next phone call -- original post suggesting -- indeed possibility, slower making calls in parallel (like code below does).

sc.initialize({ client_id: "b8f06bbb8e4e9e201f9e6e46001c3acb", }); $.getjson("http://www.json-generator.com/api/json/get/bljohiysay?indent=2", function(data){ //link of playlist var reply = {}; $.each(data.playlistarray, function(key, val){ //navigate array called playlistarray var songlink = val.url; // value of url in array sc.get('/resolve', { url: songlink }, function(track) { answer[songlink] = track; if(object.keys(answer).length == data.playlistarray.length) { // we've got results: let's process them iterating on data.playlistarray 1 time again $.each(data.playlistarray, function(key, val){ var track = answer[val.url]; $("#demo").append("<p id= "+ track.id + ">" + track.title + "</p>"); }); } }); }); });

javascript json callback jquery-deferred each

No comments:

Post a Comment