Reputation: 4379
Expanding on this question in SO Deferred in $.when while looping an array
I have this control structure:-
function oldSync(array) {
var output = []; // to store the output
$.each( array, function(key,value) { // runs sequentially
var item1 = SyncFunction_A(input);
var item2 = SyncFunction_B(input);
output.push({'a': item1, 'b': item2});
});
return doSomething(output); // process all output
}
Next, I replaced SyncFunction() with AsyncFunction(),
Question: How do I convert it to a deferred or async function?
function newAync(array) { //
var output = [];
$.each( array, function(key,value) { // runs sequentially
var item1 = AsyncFunction_A(input);
var item2 = AsncFunction_B(input);
item1.then(item2).then(function(data) {
output.push({'a': data[0], 'b': data[1] });
}
});
return doSomething(output); // FAIL, it doesn't wait for Async
}
Upvotes: 0
Views: 49
Reputation: 3418
What you need to do is take advantage of callback functions in order to use the sync functions. I have no idea what your A and B functions are, what they are suppose to do, or what those values represent that you are storing in the output
array.
Here is an example where you pass an array of urls into a function and it executes a callback when you have gotten the results for each url:
function func(urls_array, callback){ // The "callback" will be called when all results have returned.
var results = []; // Array to store the results of each $.get
for(var i=0;i<urls_array.length;i++){ // Loop through each url
$.get(urls_array[i], function(x){ // get the data at the url
results.push(x); // store the results of this get function
if(results.length == urls_array.length){ // If all urls have returned
callback(results); // execute the callback function letting it know that you have finished
}
});
}
}
Maybe this will help you understand how sync functions (functions with callbacks) work.
If you want to get a little more specific with your question than we can provide answers that might help, but what you asked is too generic and too may things, such as SyncFunction_A
are not defined for us.
Upvotes: 1
Reputation: 7159
In real i prefer to check code in sandbox. But i hope you'll catch the main idea
function newAync(array) { //
var output = [],
promises = [];
$.each( array, function(key,value) { // runs sequentially
var item1 = AsyncFunction_A(input);
var item2 = AsncFunction_B(input);
var promise = item1.then(item2).then(function(data) {
output.push({'a': data[0], 'b': data[1] });
};
promises.push(promise);
});
var defer = $.Deferred();
$.when.apply($, promises).done(function() {
defer.resolve(doSomething(output));
});
return defer.promise();
}
Upvotes: 1