在 Tableau 中使用 Promise 解析 json

Parsing Json with Promise in Tableau

本文关键字:Promise 解析 json Tableau      更新时间:2023-09-26

我正在开发 tableau,我必须构建自己的 Web 数据连接器。我写了它,它在Chrome上完美运行。但是当我在 Tableau 中使用它时,我收到一个愚蠢的错误:

ReferenceError: Can't find variable: Promise file: http://localhost:9000/json-connector line: 246

我的连接器分为两部分。第一部分调用 Web 服务以获取目标列表,并用其名称填充两个列表。第二部分调用另一个 Web 服务,以获取两个选定目标的每个路径。

我想

获取第一个列表时发生错误。我想坚持认为它适用于 chrome,但不适用于 tableau。

发生错误的代码部分:

var getJSON = function(url) {
  return new Promise(function(resolve, reject) {
    var xhr = new XMLHttpRequest();
    xhr.open('get', url, true);
    xhr.responseType = 'json';
    xhr.onload = function() {
      var status = xhr.status;
      if (status == 200) {
        resolve(xhr.response);
      } else {
        console.log("Something went wrong with the destination")
        reject(status);
      }
    };
    xhr.send();
  });
};

我认为 tableau 不支持 Promise。但我不知道如何解决。非常感谢您的帮助!

这就是我如何使用这个函数:

getJSON('http://localhost:9000/stations').then(function(data) {
    //alert('Your Json result is:  ' + data.result); //you can comment this, i used it to debug
    //result.innerText = JSON.stringify(data); //display the result in an HTML element
    console.log("starting parsing on : " + data.length);
    var listArrival = document.getElementById('Arrival'); //get the list where you want to add options
    var listDeparture = document.getElementById('Departure');
    if(listArrival == null || listDeparture == null) console.error("Impossible to retrieve the list")
    var op;
    var addedStations = [];
    for(var i = 0; i < data.length ; i++){   
        var obj = data[i];  
        var overflowControler = 0;   
        for(var key in obj){
            console.log(key + '=' + obj[key]);
            if(key == 'name' && addedStations.indexOf(obj[key]) == -1){  
                op = new Option(obj[key], obj['nlc'], true);
                op2 = new Option(obj[key], obj['nlc'], true);
                if(op == null) console.error("Impossible to create the new option")
                listArrival.add(op);
                listDeparture.add(op2);
                addedStations.push(obj[key]);
            }
            overflowControler ++; 
            if(overflowControler > maxLengthOfEachRecordFromJson) break; // overflow control
        }
        if(i > maxStationsRecordNumberFromJson) break; //overflow control
    }
}, function(status) { //error detection....
  alert('Something went wrong.');
});

按照Tomalak的建议,我在脚本中添加了一个库,Tableau能够使用Promise。

<script src="https://cdnjs.cloudflare.com/ajax/libs/es6-promise/3.2.1/es6-promise.min.js" type="text/javascript"></script>

我没有对代码进行其他更改。