0

I am stuck with how to use the variable inside a callback function from another function that is outside of callback...

Simple explanation of problem:

There is function that gets json from web. It takes some arguments already. On success, callback manipulates the data slightly. Now, another function responsible for updating the chart is meant to get the manipulated data from callback and do its own thing...

My code:

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)
);
user007
  • 45
  • 8
  • 1
    Just put the call to `changeChart()` *inside* the callback function. – Pointy Mar 28 '18 at 13:01
  • @Pointy I have several functions similar to changeChart. Do they all have to go inside callback , so I can play with the fetched data? Edit: Actually it makes no sense to put it inside, as each time I will be calling this function with different parameters... ? – user007 Mar 28 '18 at 13:24

1 Answers1

0

Just put the callback in the function like this:

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??
);
MauriceNino
  • 6,214
  • 1
  • 23
  • 60