The popular JavaScript Q module implements the concept of deferred / promises / futures. I think it is mainly used with node.js, but it also supports browser. I use it with node.js.
To make consecutive calls, you bind one promise of the following with then() , but in a loop it can be so inconsistent that I find it difficult to do the same thing as this pseudocode:
forever { l = getline(); if (l === undefined) { break; } else { doStuff(l); } }
The Q documentation includes an example that seems pretty similar:
var funcs = [foo, bar, baz, qux]; var result = Q.resolve(initialVal); funcs.forEach(function (f) { result = result.then(f); }); return result;
But trying to adapt this example to my problem, I did not succeed.
Unlike the sample code, I do not iterate over the array, but I want to loop until the end condition is met. Also, I always call the same function. My function does not accept the previous result as a parameter for the next call. Each call takes no arguments, but the return value decides whether to continue the loop.
These seemingly trivial differences cause some kind of insurmountable mental block. Now I understand why many people find it difficult to understand promises.
source share