0

I created a function that loads game map from json file.

function newTileMapFromJSON(src) {
    var mymap;
    $.getJSON(src, function(data) {

        [...]

        var finalData = {
            map: tMap,
            tiles: blocks,
            name: MapName
        };

        return finalData;
    });
}

But it won't work. There is "return" but in function inside "getJSON". I've no idea how to get "finalData" and return it.

function newTileMapFromJSON(src) {
    var mymap;
    var finalData;
    $.getJSON(src, function(data) {

        [...]

        var finalData = {
            map: tMap,
            tiles: blocks,
            name: MapName
        };

    });
    return finalData;
}

This code doesn't work, returned finalData is undefined. Maybe getJSON works in another thread? I don't know.

How would you do that, if you were me?

Piotrek
  • 10,919
  • 18
  • 73
  • 136
  • `$.getJSON` is an async call, so you'll need to use callback functions to get the data out. – ayyp Jun 04 '13 at 15:20
  • 2
    You can't. don't try to get around it. Ajax is asynchronous. – Kevin B Jun 04 '13 at 15:21
  • 1
    the "deferred" object in the linked question would be appropriate here, because you can use `.then` to pre-process the received data before passing it back to the intended receipient. – Alnitak Jun 04 '13 at 15:23
  • @Alnitak is right. You should just return `getJSON().promise()` – Andbdrew Jun 04 '13 at 15:27
  • @Andbdrew You don't need to use `.promise()` on `.getJSON()`, but it won't hurt anything either. – Kevin B Jun 04 '13 at 15:29
  • @Andbdrew there's no need for `.promise()` - the `getJSON()` result is already a promise object. I would use `return getJSON(...).then(function(data) { ... ; return finalData } })`. – Alnitak Jun 04 '13 at 15:29
  • @KevinB it can hurt - it strips the non-promise properties from the `jqXHR` object. – Alnitak Jun 04 '13 at 15:30
  • I wish I hadn't close-voted this now - sometimes it helps to give specific advice, even though the question is almost exactly the same as other questions. – Alnitak Jun 04 '13 at 15:31
  • @Alnitak when I'm returning a promise, I want to remove the non-promise properties of the jqXHR object. – Andbdrew Jun 04 '13 at 16:04
  • @Andbdrew why? They can contain useful AJAX related information. They _don't_ include the properties that allow you to change the promise's state. – Alnitak Jun 04 '13 at 16:06
  • @Alnitak I don't want consumers of my promises to be able to manipulate the state of the promise. – Andbdrew Jun 04 '13 at 17:03
  • @Andbdrew that's what I just said. You _can't_ manipulate the state of the promise with the `jqXHR` - the other "deferred" methods don't exist on it. – Alnitak Jun 04 '13 at 17:16

0 Answers0