如何在 JavaScript 的其他函数中使用回调?

用户007

我被困在如何从回调之外的另一个函数使用回调函数内的变量...

问题简单解释:

有从网络获取json的函数。它已经需要一些参数。成功后,回调会稍微操作数据。现在,另一个负责更新图表的函数旨在从回调中获取操作数据并做自己的事情......

我的代码:

var mainData;

function getMainData (city, callback) {
  this.city = city;
  var url = "http://api.openweathermap.org/data/2.5/weather?q=appid=7ce3e1102e1902e0f878c2a640e95aed&london";

  $.ajax ({
    method:  "GET",
    type:    "json",
    cache:   "false",
    url:      url,
    success:  callback
  })
};

function callback (data) {
  mainData = data;

  var dArray = data.list.map(a=>a.dt)
  var tempMinArray = data.list.map(a=>a.main.temp_min)
  var tempMaxArray = data.list.map(a=>a.main.temp_max)
}

function changeChart (chartName, howToPassTempMinArrayHere?) { // <--- this is where I have no idea how to pass callbacks variables
  chartName = chart.name.(....);
  someDataFromMainData = chart.data.(....);
};


// on click of button (...) : 
(
getMainData(callback); // why no action?? nothing??
changeChart (myChart, someDataFromMainData)
);
莫里斯·尼诺

只需将回调放在函数中,如下所示:

var mainData;

function getMainData (city, callback) {
  this.city = city;
  var url = "http://api.openweathermap.org/data/2.5/weather?q=appid=7ce3e1102e1902e0f878c2a640e95aed&london";

  $.ajax ({
    method:  "GET",
    type:    "json",
    cache:   "false",
    url:      url,
    success:  callback
  })
};

function callback (data) {
  mainData = data;

  var dArray = data.list.map(a=>a.dt)
  var tempMinArray = data.list.map(a=>a.main.temp_min)
  var tempMaxArray = data.list.map(a=>a.main.temp_max)
  
  // Put your code here
  changeChart (myChart, someDataFromMainData)
}

function changeChart (chartName, howToPassTempMinArrayHere?) { // <--- this is where I have no idea how to pass callbacks variables
  chartName = chart.name.(....);
  someDataFromMainData = chart.data.(....);
};


// on click of button (...) : 
(
getMainData(callback); // why no action?? nothing??
);

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章