while (termsEnumerator.moveNext()) { // here adds som html using arr1.push(""); var currentTerm = termsEnumerator.get_current(); $.when(GetSubTerms(currentTerm)).done(function (childItemsHtml) { //adding sub terms arr1.push(childItemsHtml); }); } //push closing html elements into arr1 dfd.resolve(arr1.join(''))
That does not work. GetSubTerms
is still asynchronous, so arr1
will not contain the childItemsHtml
s when the dfd.resolve()
is called. You will need to wait for the promises to finish before calling that! Do something like this:
function GetTerms(){
var dfd = $.Deferred();
// some variables and code here
clientCtx.load(terms);
clientCtx.executeQueryAsync(Function.createDelegate(this, function (sender, args) {
dfd.resolve(terms.getEnumerator());
}),
Function.createDelegate(this, function (sender, args) {
dfd.reject(args.get_message());
}));
return dfd.then(function(termsEnumerator) {
var promises = [];
while (termsEnumerator.moveNext()) {
// here adds som html using promises.push($.when(""));
var currentTerm = termsEnumerator.get_current();
promises.push( GetSubTerms(currentTerm) );
}
//push closing html element promise into promises
return $.when.apply($, promises).then(function() {
var arr1 = $.map(arguments, function(args){return args[0];});
//adding sub terms
return arr1.join('');
});
});
}