Google 使用异步数据调用值的 Chart DataView 计算列

Google Chart DataView calculated column using async data call values

我正在使用 DataView 计算列。我使用的calc: callValue函数需要从两个异步数据调用结果中取值,进行计算,return一个最终值。

我通常实现多个数据调用然后计算值的方式是 $.when().done()。但是,DataView 不会等到异步调用完成,而是显示空值。

我认为它在语法中,但无法理解。这是我到目前为止所拥有的。

var view = new google.visualization.DataView(data);

view.setColumns([
  data.getColumnIndex('PART'),
  { calc:  callValue, type: 'string'}
]);

function callValue(dataTable, rowNum) {

   var part = dataTable.getValue(rowNum, dataTable.getColumnIndex('PART');
   var value1;
   var value2;

   $.when(
      $.get( "https://jsonplaceholder.typicode.com/posts" ), 
      $.get( "https://jsonplaceholder.typicode.com/users" )
   ).done(function(json1, json2){
      value1 = json1[0].title;
      value2 = json2[0].website;
   })

   return part + value1 + value2;
}

如何实现我的目标...从两个异步数据调用结果中获取值,进行计算,并return一个最终值?

感谢您提供任何指导!

解决方案:调用异步数据然后在 DataView 中使用它。请参阅@WhiteHat 的评论。

since $.when is async, the return statement will always run before $.when is finished. you'll need to collect all the possible data, before creating the data view... – WhiteHat Oct 18 at 1:26