3

How can I wait for d3.json to fill my array saved_data before my function callback is executed?

I'm using saved_data if it is not empty. Otherwise I'm requesting new data and saving it in the saved_data variable:

if (saved_data.length > 0) {
  callback(null, parse(variable, saved_data)); 
}
else {
  // -------------- Begin Request New Data ------------------
  d3.json(" ... ", 
      function(data) {
        if (!data) return callback(new Error("unable to load data"));   
        saved_data = data; 
  });

  // how to wait on d3.json? before the call back?
  callback(null, parse(variable, saved_data));

}
4

1 回答 1

2
if (saved_data.length > 0) {
  callback(null, parse(variable, saved_data)); 
}
else {
// -------------- Begin Request New Data ------------------
  d3.json(" ... ", 
      function(data) {
        if (!data) return callback(new Error("unable to load data"));   
        saved_data = data; 
        // Put it here.
        callback(null, parse(variable, saved_data));
      });
} 

Put it in the same callback for d3.json

于 2013-08-12T21:44:14.623 回答