AJAX stands for
Asynchronous Javascript And Xml. The key word there is "Asynchronous" - the
$.ajax(...)
call returns
before the request has been made, so none of the results are available. You are returning an empty array, which will be populated at some point in the future.
You need to re-think how you call the code. Rather than returning the array, you need to return a
promise of an array. The code which uses the array needs to be moved to a continuation on that promise.
function getFriendsOfUser(steamID){
var steamFriendIDs = [];
var promise = $.Deferred();
if (steamID === null || steamID === "") {
url = "http://api.steampowered.com/ISteamUser/GetFriendList/v0001/?key="+_steamAPI+"&steamid=76561197960435530&relationship=friend";
}
else {
url = "http://api.steampowered.com/ISteamUser/GetFriendList/v0001/?key="+_steamAPI+"&steamid="+steamID+"&relationship=friend";
}
$.ajax({
dataType: "json",
url: url
}).done(function(data){
$.each(data["friendslist"]["friends"], function(index, value){
steamFriendIDs.push(data["friendslist"]["friends"][index]["steamid"]);
});
promise.resolve(steamFriendIDs);
}).fail(function(jqXHR, textStatus, errorThrown){
promise.reject(jqXHR, textStatus, errorThrown);
});
return promise.promise();
}
function example(){
getFriendsOfUser(steamID).done(function(friendList){
console.log(friendList);
});
}
Deferred Object | jQuery API Documentation[
^]