Say I have a very long list where each element requires an asynchronous call to fetch. I would like to write an API on top of that list so that a consumer can simply call "next()" or otherwise synchronously iterate over the list.
Ideally I would have something that looks like this:
while ((foo = generator.next()) != null) {
process(foo);
}
But, I find myself tripping over the semantics of deferred calls, and I don't know how to escape this hard-coded pattern into a generic loop:
$.when(foo).then(process1AndFetch2)
.then(process2AndFetch3)
.then(process3AndFetch4)
...
Presumably, I could do this myself with callbacks
var callback = function() {
process();
fetch(callback);
}
fetch(callback);
But then my stack would get very deep, which is why I was working deferreds.
Are there any usual suspects for turning this kind of asynchronous behavior into a synchronous API?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…