Javascript: Loop with Deferred Calls

    This is a solution I can across that really helped me out in a bind. I need to use a for loop with a series of calls, and each call took sometime to execute. So I looked at how I could make the calls asynchronous rather than synchronous.

(function def() {
		var def = (new $.Deferred()).resolve();
		var list = new Array(15);//My hacky way of doing it.
		$.each(list, function (index, val) {
			def = def.pipe(function () {				
			return calls(index);
This example doesn't completely show the advantages but more of how the concept work. With my problem what I had was a multi-leveled or hierarchy rather leveled system of data. So data that I requested was start at the top level and return lower levels, then with values I would request the data for each values' lower level. This process worked for me but I'm not able to completely show for a number of reasons.

    If you look at the results you will see that I do not preserve the order and it is not guaranteed. If this isn't a problem then you all set. If you want to, what I did was pass the index's value as a second parameter and keep track of things that way. Also could use your values that used for the ajax call. Say you have a unique value to the api that requests the data then use that to track what order they should be listed. If you have a list of those values and order it based on the same list then it will be preserved.


Popular posts from this blog

Installing Windows on Acer chromebook 15 cb3-532

Entity Framework: ToListAynsc & WhereAsync

CSharp Cheatsheet