1

Not sure how to title this problem, but I'm trying to return an object and RequireJS doesn't wait for the asynchronous function to finish:

define([
    "d3"
],
function(
    d3
) {
    var helper = {};

    helper.foo = function() {
        return "bar";
    }

    helper.bar = "hey!";

    d3.json("/data/my_data.json", function(json) {
        helper.data = json;

        return helper;
    });

    // return helper;
});

Now if I use helper in another script then it's undefined. If I move the return helper outside the d3.json() function (comment the first return and uncomment the second) then helper.foo and helper.bar is defined, but helper.data is undefined.

What is the best way to make RequireJS return helper.data?

hobbes3
  • 28,078
  • 24
  • 87
  • 116
  • 1
    The solution is the same as in any other case, you need to design your code to account for the asynchronous nature of the computation. RequireJS is not special in this regard. – Louis Aug 18 '16 at 10:31
  • Is it ok to have multiple JS files on the same page load the same JSON file? I thought it would be more efficient to load the JSON once then pass that data to the other JS files. That's why I was trying to do it with RequireJS. – hobbes3 Aug 19 '16 at 01:02
  • 1
    It is definitely more efficient to load it just once. But when I look at your code I'm not seeing you loading it with RequireJS. You are loading it with `d3.json`. If you were loading it with RequireJS you'd put a dependency like `foo.json` in a `define` or `require` call. – Louis Aug 19 '16 at 10:23
  • Thanks. I figured it out by writing a `main.js` script that loads the data once, then calling the other functions in other files (which uses `define()`) to draw the individual `svg`. – hobbes3 Aug 21 '16 at 06:12

0 Answers0