Avoid the callback hell and improve on promises in node.js and JavaScript by using the new ES6 generators.
This presentation will show you before and after code examples that will illustrate the full benefit of using this new syntax.
What's New in Teams Calling, Meetings and Devices March 2024
Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (and CoffeeScript)
1.
2. Aboutme
•Several production-grade node apps in the wild
•muuuf
•Up & Front
•EthPort(using what I show today)
•The others I cannot mention
•Maintainer of named-routes, help out at CoffeeScript, bluebird and sequelize
•Berlin Node.js (550 members)
•Actually a MathsPhD
3. SomecodeI saw
CodeSchool’sBasecamp Search, Code written in RoR
And I thought “Hey, it’s really been some time since I saw such clear code in node. There’s gottabe a way!”
5. Can we do better?
Yes, remove error-checking by using promises. Have one error-catcher (domain) outside the controller logic.
Somewhat better -still twists your head reading it. Also, you lose variable scope as you move down the chain.
7. This isimpossible*…
*of course you could write synchronous C extensions that would provide this, but say goodbye to performance
8. This isimpossible*…
*of course you could write synchronous C extensions that would provide this, but say goodbye to performance
9. Event Queue
The reliance on callbacks is due to what is arguably JavaScript’s best feature –its event queue. Instead of using subprocessesor threads, it processes events sequentially as they come in.
Thus, calling I/O MUST delegate back or everything will come to a halt.
10. Performance
Concurrentusers
Response time
Server CPU usage
http://blog.loadimpact.com/2013/02/01/node-js-vs-php-using-load-impact-to-visualize-node-js-efficency/
node.js
11. Performance
Concurrentusers
Response time
Server CPU usage
http://blog.loadimpact.com/2013/02/01/node-js-vs-php-using-load-impact-to-visualize-node-js-efficency/
node.js
PHP
12.
13. So, ES6?
Gives us generators. For this discussion, they are like functions that can be paused and continued at a later point in time.
Let’s code.
24. Towrapup
•‘yield’ makes code clearer, better readable and more maintainable
•Start using this! 0.11.13 runs two of my production websites without any hiccups (0.11.14 has some edge case memory leaks)
•Use co and/or bluebird in all places, transform third- party libraries using thunkifyor bluebird’s promisify
•If possible, replace express with koa(also gives you named routes for free)
•Finally, my benchmarks of stress testing a real-life app before and after an express-to-koamigration could not measure any performance difference in terms of requests served and an increase of memory consumption by 10-15 MB. Absolutely worth it!