-
-
Save jswartwood/1570839 to your computer and use it in GitHub Desktop.
| <!DOCTYPE html> | |
| <html> | |
| <body> | |
| <p>These should output "last", "ok", then "all" for 10 promises and then another 10.</p> | |
| <div id="out"></div> | |
| <script type="text/javascript" src="https://raw.github.com/briancavalier/when.js/dev/when.js"></script> | |
| <script type="text/javascript" src="main.js"></script> | |
| </body> | |
| </html> |
| var out = document.getElementById("out") | |
| , lastPromise | |
| ; | |
| for (var i = 0; i < 10; i++) { | |
| (function( pos ) { | |
| var andDefer = when.defer() | |
| , allPromises = [ lastPromise, andDefer ] | |
| ; | |
| when(lastPromise).then(function() { | |
| out.innerHTML += "last done: " + pos + "<br>"; | |
| }); | |
| lastPromise = when.all(allPromises).then(function() { | |
| out.innerHTML += "all done: " + pos + "<br>"; | |
| }); | |
| andDefer.then(function( val ) { | |
| out.innerHTML += val + ": " + pos + "<br>"; | |
| }); | |
| setTimeout(function() { | |
| andDefer.resolve("ok"); | |
| }, 1000); | |
| })(i); | |
| } | |
| setTimeout(function() { | |
| out.innerHTML += "<br>"; | |
| for (var i = 0; i < 10; i++) { | |
| (function( pos ) { | |
| var andDefer = when.defer() | |
| , allPromises = [ lastPromise, andDefer ] | |
| ; | |
| when(lastPromise).then(function() { | |
| out.innerHTML += "last done: " + pos + "<br>"; | |
| }); | |
| lastPromise = when.all(allPromises).then(function() { | |
| out.innerHTML += "all done: " + pos + "<br>"; | |
| }); | |
| andDefer.then(function( val ) { | |
| out.innerHTML += val + ": " + pos + "<br>"; | |
| }); | |
| setTimeout(function() { | |
| andDefer.resolve("ok"); | |
| }, 1000); | |
| })(i); | |
| } | |
| }, 10000); |
Nice. Yes, that is more akin to what I was looking for, although the API for the module got a little twisted in all of that. I've just done a new push to https://github.com/jswartwood/and1 to finish out my first-draft prototype. Now, I just need a little simplification (if possible); I'll be looking to merge in aspects of your Promises/A example above to clean out some of those pesky defers (I even ended up adding another in jswartwood/and1@13b3cb7). I'm going to throw some doc in the code when I get home to explain my intentions for the usage.
Also, I'm thinking that any further queue conversation should probably move to jswartwood/and1#1; it has become less about the initial hiccup (of misordered "last done: 1" vs "ok: 0") and more about the actual queue implementation.
Cool. Feel free to @ me on that issue if you have any more when.js questions.
I'm betting you know this already, but these two are essentially equivalent:
The second one will create 1 fewer promise, and so be (negligibly) faster, and will probably compress slightly better. Otherwise, you won't notice a difference.