CQM
CQM

Reputation: 44228

jquery ajax, where to do asynchronous computations after GET call

ajax in jQuery with the request type, url, success functions. A lot of times I am expecting a JSON response.

My problem is that I then need to reformat the json arrays into a different structure. This has the potential to be computationally expensive and I would like to do that asynchronously too.

How would that syntax look, do I just put another $.ajax nested within the success portion of the previous ajax call. Or is there a more clever way of writing this where it does the network call, returns json and then allows me to manipulate the response all within the asynchronous thread

Thanks for any insight

Upvotes: 1

Views: 101

Answers (2)

Mike Robinson
Mike Robinson

Reputation: 25159

If it really is expensive, sounds like you need a web worker:

https://developer.mozilla.org/en-US/docs/DOM/Using_web_workers

Dedicated Web Workers provide a simple means for web content to run scripts in background threads. Once created, a worker can send messages to the spawning task by posting messages to an event handler specified by the creator.

There's some caveats, but was created for what you described. Must be a heck of a lot of JSON to be an issue though.

Upvotes: 3

graphicdivine
graphicdivine

Reputation: 11211

I'm not sure I 100% understand the question, but I think what you want to do is something like this, a simple function call. It's not really asynchronous, though, except in that it will only fire when it has data:

function reformat(data){
    ... reformat your data here ...
}

$.ajax({
    url: "yoururl.xyz",
    success: function(data){
         reformat(data);
    }
});

Upvotes: -1

Related Questions