Last active
October 10, 2015 18:06
-
-
Save ostgals/8c95160500350616cfff to your computer and use it in GitHub Desktop.
Snippet - Multi-thread queue with jq's promises
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
// ..... | |
enqueue: function(items, get_promise, num_threads){ | |
num_threads = num_threads || 1; | |
var dfd = $.Deferred(), i = 0, num_total = items.length, num_active = 0, num_done = 0, | |
next = function(){ | |
while (num_active < num_threads && i < num_total) { | |
num_active++; | |
get_promise(items[i++]).done(function(){ | |
num_active--; | |
dfd.notify(++num_done, num_total); | |
if (num_done == num_total) dfd.resolve(); | |
next(); | |
}); | |
}); | |
}; | |
next(); | |
return dfd.promise(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment