0

I'm using jQuery $.when function to synchronize two $.getJSON asynchronous calls I have. Merging the data from both calls now works fine, however I want to return the contents of the merge , which is an array of jQuery objects.

I'm trying to achieve this using a $.when function wrapped around another function which contains the code where I synchronize my asynchronous calls. My code looks like this:

 $.fn.getResultFromMergedJsonCalls = function(params){ $.when( $.fn.jsonCall1(params), $.fn.jsonCAll2(params) ).then(function(){ var mergedData = mergeResults(resultOfJsonCAll1,resultOfJsonCAll2) return mergedData; }); }; ) 

How can I return the contents of the mergedData array to a calling function , i know the nature of the asynchronous calls is causing this behavior so i just need a pattern that solves the problem. Thanks.

2
  • You can't. It's asynchronous. You have to process the result inside the callback you pass to .then, or pass it to a function called from inside the callback. Commented Dec 16, 2011 at 14:32
  • 2
    You usually don't call $.fn functions directly. Commented Dec 16, 2011 at 14:35

2 Answers 2

3

Pass a callback function to getResultsFromMergedJsonCalls, then invoke the callback from the then handler. For example:

$.fn.getResultFromMergedJsonCalls = function(params, success){ $.when( $.fn.jsonCall1(params), $.fn.jsonCAll2(params) ).then(function(){ if (success) { var mergedData = mergeResults(resultOfJsonCAll1,resultOfJsonCAll2); success(mergedData); }); 

};

The caller of getResultsFromMergedJsonCalls of course must implement a suitable function to pass as that new, callback argument.

Sign up to request clarification or add additional context in comments.

Comments

2

That's asynchronous; you can't return it.

Instead, you need to pass the value back using a callback.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.