I am using a when,done ajax call for the two links. But how do I bring the data out scope, so I can use it in another function.
mysetup:
var urlS = "https://api.twitch.tv/kraken/streams/freecodecamp?callback=?";
var urlC = "https://api.twitch.tv/kraken/channels/freecodecamp?callback=?";
var twitch = function(urlS, urlC) {
var status = $.getJSON(urlS);
var channel = $.getJSON(urlC);
$.when(status, channel).done(function(status, channel) {
var stat = status[0],
chan = channel[0];
});
};
/* want to use data out of this twitch function */
What do you have in mind? You could initialize a variable outside the promise’s scope and set them inside the $.done
call, but it would be better to just call whichever functions you want to use inside of $.done
. Remember, you’re not just dealing with scope here, but a possible race condition where some other function could be called before $.done
, and would then be missing those variables.
i tried setting a global variable and set the data to the global variable inside the done, but it did not work for me.
I have an array of users and i want to use map function to generate the links. Then pass in the links into the promise function and have it return an the necessary data i need in an object. Then use a for loop for my new object to create a table.
Yeah, you’ll want to use the code you’ve defined above per user, and then do your DOM manipulation inside of the $.done
call.
arrayOfUsernames.forEach(function(usename) {
var urlS = "https://api.twitch.tv/kraken/streams/" + username + "?callback=?";
var urlC = "https://api.twitch.tv/kraken/channels/" + username + "?callback=?";
var twitch = function(urlS, urlC) {
var status = $.getJSON(urlS);
var channel = $.getJSON(urlC);
$.when(status, channel).done(function(status, channel) {
var stat = status[0],
chan = channel[0];
//Add markup here
});
};
}
I highly suggest using Moustache templating. Check out these two videos for a quick example of this in action:
jQuery Ajax Tutorial #3 - Delegating Events & Mustache.js Templating
jQuery Ajax Tutorial #4 - “Edit” modes & Better Mustache.js
It might seem like a lot to take in, but it’ll make your life a lot easier.
A common solution to this problem is to put one AJAX function inside the other one like this.
$.getJSON(urlS, function(streamdata){
status = streamdata;
$.getJSON(urlC, function(channeldata){
channel = channeldata;
// put all of the code that depends on the JSON data in here
});
});