【问题标题】:Use variable from inside $when...then() outside the function在函数外部使用 $when...then() 内部的变量
【发布时间】:2019-12-12 13:37:54
【问题描述】:

来自Use variable from one forEach Method in another 的跟进。如何在函数外部使用我在 then() 中获得的值?

var first, second;
$.when(
  $.getJSON(json1, result => first = result);
  $.getJSON(json2, result => second = result);
).then(function() {
  if (first && second) {
    let results = first.map((item, index) => item.x / second[index].v);

  }
});

我想在这个函数之外的另一个函数中使用results

我想在 highcharts 中使用这些 results 值。

有没有办法做到这一点?

【问题讨论】:

标签: javascript jquery json function highcharts


【解决方案1】:

在回调函数中初始化 Highchart.js。

var first, second;
$.when(
  $.getJSON(json1, result => first = result);
  $.getJSON(json2, result => second = result);
).then(function() {
  if (first && second) {
    let results = first.map((item, index) => item.x / second[index].v);

    Highcharts.chart('container', {
      ...
    });
  }
});

【讨论】:

  • 我在输入控制台日志时收到undefined
  • @noob 我明白你想要什么。你必须在回调函数或 Promise 链中做一些事情。
  • 我该怎么做?对不起喜欢我的网名,我真的是菜鸟
  • jsfiddle.net/rprak0605/kc9g5vrh ,json是我原始代码中的url。但我创造了一个小提琴
猜你喜欢
  • 2014-03-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-20
  • 1970-01-01
  • 2012-07-14
  • 1970-01-01
  • 2019-12-10
  • 2022-11-27
相关资源
最近更新 更多