3 ms·
I want to like generators for asynchronous code, but the one thing that disappoints me about generators is how awkward it is to write code that does the same as
by NathanKP 12y ago
I want to like generators for asynchronous code, but the one thing that disappoints me about generators is how awkward it is to write code that does the same as an async.auto
I use async.auto because of the ease of adding new asynchronous functions that depend on one or more other asynchronous functions having been executed beforehand.
Simply put you can break up a task into steps that depend on each other, and the steps run whenever all their dependencies have been executed. You don't have to worry about whether the functions run in series, or parallel, you just define that one function depends on another and it just works.
I have yet to see a promise example, or a generator example that had the combination of maintainability and legibility that an async.auto has. What I really want to see is a reasonably complicated task that has say 8 or more asynchronous steps mocked out in generators. Say something like:
Post a social item
1) Write social item to database
2) Write reference to social item in feed of person who posted item
3) Fetch friends of user who posted item
4) Fetch notification settings of each friend
5) Add a reference to the social item to each friend's personal activity stream
6) Based on notification settings of each user send an email alerting each friend of the event
7) Invalidate activity stream cache key for poster, and friends
In this flow:
1 & 3 can run in parallel at the start as they don't depend on anything
2 & 5 can run as soon as 1 is finished as they depend on the ID of the object in #1
4 & 5 can run as soon as 3 is finished as they depend on the friend list
6 can run as soon as 4 is done as it needs to know who to email and who not to email
7 can run as soon as 2 & 5 are done as the streams must be updated before the cache can be cleared
With async.auto it is easy to create 7 async functions and define the dependencies, then sit back and watch it run efficiently and magically. Later if you need to add more actions it is easy to insert another function, define what it depends on and see it working.
I still don't understand how to do something like this with generators, and none of the examples I've seen so far is complex enough, nor do they seem to solve this problem in a format as clean as async.auto