4 ms·
Generators are sweet, but you can use just Promises or the async.js library to write nice flat code. No callback hell / play button shaped code.
by scoin 10y ago
Generators are sweet, but you can use just Promises or the async.js library to write nice flat code. No callback hell / play button shaped code.
- masklinn 10y agoWhile they allow limiting the rightsward drift of code, explicit promises are still event emitters and still require a significant amount of callbacks if you don't have generators or async functions.
- drostie 10y agoThe nice thing about the generator is that (with a nontrivial amount of boilerplate!) you can pretend that the body of the function* is a synchronous zone even though it makes several calls to asynchronous promises. The basic idea is that you wrap the generator in a sort of trampoline that turns it into a promise. This 'trampoline' detects whenever the generator falls down to it (via some `yield` of some Promise) and then waits on that promise before resuming the generator-trampoline combo. The promise then returns its result directly into generator.next(), where it becomes the value of the `yield` expression, thus within the generator `x = yield myPromise()` creates a new Promise by calling myPromise, suspends execution until that Promise completes (by dropping down to the trampoline, which bounces us up into the myPromise().then()), and finally gets the value and assigns it to x. You have just one scope, the scope of the function* of the generator, in which all of the results of all of your Promises live.