I've been struggling with a seemingly simple task that's been causing me immense frustration. Despite scouring the entire Internet, none of the solutions I found seem to directly address my specific issue. It all stems from a follow-up question related to JavaScript - no return
Below is the code snippet in question:
var worksheetArray;
var filtersArray =[];
function testu(){
filtersArrayFetch();
console.log("finished fetching");
console.log(filtersArray);
//perform more operations on the 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");
}
To explain in simpler terms - I have an array of worksheets fetched using synchronous Tableau API function. The getFiltersAsync()
function returns a Promise as an Array. My goal is to extract the field names using getFieldName
and store them in a final Array for later use in the code. Everything seems to work up until
worksheetArray[i].getFiltersAsync()
, but it fails to evaluate the .then()
method and ends up returning undefined to the testu()
function. This function is triggered by a button click event.
I must ensure compatibility with IE (Edge), so using Promise.all() is not a viable solution.
What could be causing the script to malfunction? Why isn't it processing the .then()
method?
UPDATE:
I was able to resolve the issue by implementing a 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();
}