Hello All, I have a simple method to get portal users by a role and put them in an array and return the array. Please see codes below. When I call the method and log the result, the array has two objects. But when i log the length of the result array, i got 0. The length should be 2, why 0 was returned? Is this related to the deferred object? I have no idea how to deal with deferred object. Please help!
results:
Solved! Go to Solution.
Alex,
You are checking the length of the array before the deferred has been returned. One way to resolve this is to make your function a deferred as well:
getUsersByRole: function(portal, param) {
var users = []
var def = new Deferred;
portal.queryUsers(param).then(lang.hitch(this, function(items){
if (items && items.results.length > 0){
array.forEach(items.results, lang.hitch(this, function(item){
var u = {};
u.username = item.username;
u.fullName = item.fullName;
users.push(u);
}));
def.resolve(users);
}
}));
return def;
},
and then simply call your deferred function like this:
portalHandler.getUsersByRole(this._portal, {q: 'role:' + 'org_user'}).then(function(result){
console.info(result.length);
});
Alex,
You are checking the length of the array before the deferred has been returned. One way to resolve this is to make your function a deferred as well:
getUsersByRole: function(portal, param) {
var users = []
var def = new Deferred;
portal.queryUsers(param).then(lang.hitch(this, function(items){
if (items && items.results.length > 0){
array.forEach(items.results, lang.hitch(this, function(item){
var u = {};
u.username = item.username;
u.fullName = item.fullName;
users.push(u);
}));
def.resolve(users);
}
}));
return def;
},
and then simply call your deferred function like this:
portalHandler.getUsersByRole(this._portal, {q: 'role:' + 'org_user'}).then(function(result){
console.info(result.length);
});
Worked! Thanks Robert. I have learned a lot from you. Now i know how to deal with a deferred object. But I have another issue if you don't mind to answer it here.
How can I assign the result to a variable under this scope within the call back? Please see codes below. Console outputs null. I can put all the work within the callback, but just wondering assign the result to a this scope variable to be used in other methods.
Alex,
Again it is a timing issue as your console.info(this.users) is executing before the deferred has returned.
thanks Robert. So i have to either put all the logics within the call back, or use deferred again, right?
Alex,
Yes or you can call another function from the deferred result that way your code will wait for the deferred execution.