I sat down to build yet another user registration system last night for a side project and found myself in a familiar place. I had some control flow logic that was dependent on the result of an async method. Off we go to promise land (not to be mistaken with the Promised Land).
This code sucks. I can’t read this and it barely does anything yet. Email address verification, model validation, and some additional async database queries will be necessary to completely set up this user account. This is where generators come in handy.
If you don’t know about generators, Mozilla has some nice documentation. Here is one of their examples:
Co wraps generators into a method which allows you to yield to functions that return objects, arrays, promises, thunks, or generators themselves. Using co, I am able to rewrite my user registration like so:
This is much better. I can read this code and control flow doesn’t throw my logic into a state of chaos.
If you have a codebase full of nested promises and callbacks,
npm install co.