Reputation: 672
This function is not letting me to pass data outside the function. It returns the correct data, but whenever i try to add it to an array or similar outside the function, it will not return anything. I am aware of some redundant json parse's and stringifies, but please ignore that. Ive tried setting global variables without any luck.
var item.jid = 342323; //example
p = connection.vCard.get(item.jid);
p.done(function(vCard) {
var json = JSON.stringify(vCard);
var json = $.parseJSON(json);
$(json).each(function(item,val) {
$.each(val,function(k,v) {
var json2 = JSON.stringify(v);
var obj = JSON.parse(json2);
var what = obj.BINVAL;
if(what != undefined) {
var bgimg = what;
bgimg = "data:image/jpeg;base64,"+bgimg;
//console.log(bgimg); //This returns correct data, but only from within this each loop.
//return bgimg; //this does not return anything
//arr.push(bgimg);//this does not push anything to array
//console.log(item.jid); //does not return global var
}
});
});
});
EDIT
Heres the function im trying to pull of (with changes from romy's answer) for further clarification: I am building a contactroster with avatars.
var bgimg=null;
var arr = new Array();
function getAvatar(vCard) {
var json = JSON.stringify(vCard);
var json = $.parseJSON(json);
$(json).each(function(item,val){
$.each(val,function(k,v){
var json2 = JSON.stringify(v);
var obj = JSON.parse(json2);
var what = obj.BINVAL;
if(what != undefined){
bgimg = what;
bgimg = "data:image/jpeg;base64,"+bgimg;
arr.push(bgimg);
//console.log(bgimg); //This returns correct data.
}
});
});
};
function getRoster(){
connection.roster.requestRoster(function(roster){
var items = roster.getItems();
for( var i = 0; i < items.length; i++ ){
var arr = new Array();
var item = items[i];
var thejid = item.jid;
var thename = item.name;
arr.push(thejid);
arr.push(thename);
p = $.Deferred();
p = connection.vCard.get(item.jid);
p.done(function(vCard) {
getAvatar(vCard);
});
p.resolve();
console.log(arr);
var theavatar = //This would return whatever the deferred function would throw me.
$('.sidebar-nav').append("<li class='contacts'><div id='"+thejid+"' class='avatar' src='"+theavatar+"'></div><a href='#' class='"+thejid+"'>"+thename+"</a></li>");
}
Upvotes: 1
Views: 185
Reputation: 148524
You are in async/deferred execution mode.
I dont see any benefit ( it won't work either) to return as you did :
You can use global variable if you want :
var d = $.Deferred();
var myResult=null;
d.done(function (a){ myResult=a;}) .done(function (){ alert(window["myResult"])})
d.resolve(1); //will alert "1"
but I'd prefer :
var d = $.Deferred();
function doWhatever(x)
{
//do wtf you want
alert(x)
}
var myResult=null;
d.done(function (a){ doWhatever(a)});
d.resolve(1);
http://jsbin.com/potula/1/edit
Upvotes: 1