I have fairly simple task but it makes me pull my hair out. Already searched whole Internet and none of the solutions found can be directly translated to my problem. It's a follow up question to JavaScript - no return
Here's what I got:
var worksheetArray;
var filtersArray =[];
function testu(){
filtersArrayFetch();
console.log("finished fetching");
console.log(filtersArray);
//do more stuff with array
}
function filtersArrayFetch()
{
workbook = viz.getWorkbook();
sheet=viz.getWorkbook().getActiveSheet();
worksheetArray = sheet.getWorksheets();
for (var i=0; i<worksheetArray.length; i++) {
(function(num){
worksheetArray[i].getFiltersAsync()
.then(function(promise){
for (j=0;j<promise.length;j++)
{
filtersArray.push(promise[j].getFieldName());
}
})
})(i);
}
console.log("after for");
}
In plain English -I have an array of worksheets fetched with synchronous Tableau API function. getFiltersAsync()
returns Promise as an Array. On this Array I would like to perform getFieldName
and push it to final Array I will be using later in the code. Code works until worksheetArray[i].getFiltersAsync()
but does not evaluate .then()
and returns undefined to testu()
function. testu()
is being called by button click.
I need to keep IE(Edge) compatibility so Promise.all() is not an option.
What is wrong with the script? Why it's not evaluating .then()
?
EDIT:
I've managed to solve the problem using self-invoking runner function:
function filtersearch2(i){
workbook = viz.getWorkbook();
sheet=viz.getWorkbook().getActiveSheet();
worksheetArray = sheet.getWorksheets();
var filtersArray=[];
var d=$.Deferred();
(function runner(i){
worksheetArray[i].getFiltersAsync().then(
function(filtersArrayReturnedInPromise){
for (z=0;z<filtersArrayReturnedInPromise.length;z++){
field = filtersArrayReturnedInPromise[z].getFieldName();
if (field.search("AutoFilter")>0 && field.search("Action")==-1 ){
filtersArray[filtersArray.length]=field;
}
}
if (i==worksheetArray.length-1){
var uniq = filtersArray.reduce(function(a,b){
if (a.indexOf(b) < 0 ) a.push(b);
return a;
},[]);
console.log("resolving filtersearch");
d.resolve(uniq);
} else {
i++;
runner(i);
}
});
})(i)
return d.promise();
}