How does one avoid callback hell with regards to JavaScript?
-
How to build javascript code that is complex and easy to read? Developers (including me) initiating a webapp development process, using an certain pattern or way of write javascript, thinking that this approach is the recommended one and after a minimun time, the webapp grows and you start to see cyclical depencies, callbacks inside of callbacks, one file looks like an OO class, other file is only a module, some part of the code is in closures and others parts not... the messy list of concepts goes on and on. And things get worst when you have more than one developer per app. If each developer introduce their habits inside the code, (because javascript is that much flexible) pretty fast the webapp is transformed into a frankenstein that is really hard to maintain. So again, what advices, patterns, frameworks could minimize or resolve completely this situation?
-
Answer:
There are many thing in this. I will put it in some points. Again this is my opinion and what I have seen from my experience: First of all the most important thing is no matter what you decide in terms of using patterns, code style. It has to be something that you team is doing together. If required document it. So that even if a new developer will join things will still go in same way. Define a Style guide for your project. Google has one for JavaScript https://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml . Addy osmani has one awesome blog on that http://addyosmani.com/blog/javascript-style-guides-and-beautifiers/. Read it with team discuss it and come up with something that works best for your team. There are some Great books from Addy Osmani about Design patterns in JavaScript applications: http://addyosmani.com/resources/essentialjsdesignpatterns/book/ and http://addyosmani.com/largescalejavascript/. They give a great idea. Best approach to write maintainable code in JavaScript is to write modular code. Again Addy Osmani hits best with his book http://addyosmani.com/writing-modular-js/ (All these books are free online :) ) There is no way you are going to have productivity if people who are working on project don't know much of JavaScript. I would suggest reading couple of books as a team or individuals: http://www.amazon.com/Maintainable-JavaScript-Nicholas-C-Zakas/dp/1449327680 , http://www.amazon.com/Testable-JavaScript-Mark-Ethan-Trostler/dp/1449323391/ref=pd_sim_b_1?ie=UTF8&refRID=07JARDHK1738WDEAF08K and http://www.amazon.com/Performance-JavaScript-Faster-Application-Interfaces/dp/059680279X/ref=pd_sim_b_4?ie=UTF8&refRID=07JARDHK1738WDEAF08K Regarding your concern of having so many callbacks. Use Promises. Its super easy to build Promises. They are natively coming to JavaScript in ECMAScript 6. Here are couple of tutorials that I used: http://www.slideshare.net/xmlilley/mastering-async-io-in-javascript-promises-async-190913 and http://www.slideshare.net/domenicdenicola/callbacks-promises-and-coroutines-oh-my-the-evolution-of-asynchronicity-in-javascript One thing which is very very important is using some automation tools that can help you in getting immediate feedback in terms of bugs and bad code. I personally Love Grunt http://gruntjs.com but use it through Yeoman http://yeoman.io. Its simply awesome. Use something like JSHint or JSLint with Grunt to get immediate feedback for your JavaScript code. I use sublime as editor I have installed jslint plugin in sublime. So that I can lint my files while I am writing code. One more thing which is very very important is wring tests for your JavaScript. No matter what design pattern you use how good your code is you will have bugs. Writing tests is best way to find bugs. Another important thing which most of the people don't agree is having same set of environment for each developer. Try to use same tools for your project. We generally keep a iso image for our dev machine somewhere. Whenever somebody new joins project he will install from that iso machine. Which already includes all the required tools. But if you don't wanna do this. Grunt helps you to solve this issue. Again this is just opinion. Feel free to discuss with your team. Share knowledge. These things take time. You can not read a blog or a book to change projects. It is a process and you have to go through it. You will fail many times and you will have arguments but that is what makes it interesting. I hope I have tried to answer your questions.
Pawan Chopra at Quora Visit the source
Other answers
Use a framework like Backbone JS to split up your code into manageable view and controller blocks.
Leo Romanovsky
I like to use promises (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). They allow you to turn nested callbacks such as these: getProfileById(id, function (err, profile) { if (err) return console.error(err); getFriends(profile.friends, function (err, friends) { if (err) return console.error(err); getFriendsPosts(friends, function (err, posts) { if (err) return console.error(err); UpdateView(profile, friends, posts); }); }); }); into this: getProfileById(id) .then(getFriends) .then(getFriendsPosts) .catch(function (err) { console.error(err); }); Now, browser support is a bit dodgy at the moment, but I prefer to use https://github.com/petkaantonov/bluebird anyway. It's a promise library that offers a polyfill (back to IE7) and extra features (such as promisification: http://bluebirdjs.com/docs/features.html#promisification-on-steroids). In ES6 you can also use generator functions (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*), but you can't polyfill those and I haven't really tried them out outside of a few test applications. Still, nice to have a variety of choices.
Kristjan Tammekivi
Callbacks are an essential part of JS which allows asynchronicity. We should embrace them dearly. I am not an expert in JS so you may choose not to take me very seriously but please read on. So everybody can start coding in JS pretty quickly. However owning the language is really something different. It will take time and a lot of coding. I have read tons of books and have an idea on most of the complicated aspects of this language. However i have to do many years of coding before i gain reflexes and can say i am an expert, which as of today i am greatly lacking. A developer can switch from C++ to Python, yielding sort of syntax change into a more readable, maintainable scripting environment. However with JS it's not only the syntax changing. In JS the approach to handle things are somewhat different. There are things which are nonexistent in some other mainstream languages such as prototypal delegance (i won't say inheritance), no classes, natural asynchronicity built in the callback architecture, functional scopes and closures etc... To where i want to come is, anybody coding Python at the backend and switching to JS at the frontend has to switch his mindset too. This might be really annoying to many people resulting performance loss. I am sure some do it perfectly well but probably many end up with a simplistic JS regardless of how much they are good at Python. Here comes the beauty of full stack JS. I think a web app developer should primarily focus on JS to gain the experience to harness JS at it's best. I am sure callbacks are not any hell for a full stack JS developer after some time and coding since s/he can quickly see what's going on. I have seen a beautiful answer in the topic by which i want to copy here with a little bit of a touch. Considering a hypothetical language, cascaded IO requests look like this, 1 2 3 4 var a = readFileContents("a.txt"); var b = readFileContents("b.txt"); writeFileContents("ab.text", a + b); console.log("we are done"); 2nd line starts only after 1st line finishes reading from the db. This type of program halts execution till it retrieves data from readFileContents method. In node, same would be implemented as 1 2 3 4 5 6 7 readFileContents("a.txt", function (a){ readFileContents("b.txt", function (b){ writeFileContents("ab.txt", a + b, function(){ console.log("we are done"); }); }); }); you call the function readFileContents at line 1 and continue at line 8. No blocking. If you notice, our simple logic has complicated code to read, however we can write once but later on it is difficult to understand what is happening here. Yes it looks complicated but I have to say that it's all about experience to quickly see logic behind this and it's beautiful. I feel like when i felt the first time i've understood the recursive procedures of Pascal, which was many many years ago. Besides... I have noticed that nobody under this topic has ever mentioned the importance of commenting. I believe commenting in the code and in the VCS of your choice is an highly important aspect of understanding what's going on there. No? Edit: Checking up with 's answer i concluded that he has a solid point. New JS interpretations like ES6 https://developer.mozilla.org/tr/docs/Web/JavaScript/Reference/Global_Objects/Promise introduces some level of simplification to the callback structure for a human being. However then a compatibility issue arises since even the current versions of the mainstream browsers support ES6 only partially. Given that still the corporate user's un-upgradable browser is taken into account it's a big no no to touch ES6 while developing web applications. Having said that you may still develop a Git branch of your code in ES6 and then "transpile" (i have to admit, i use this word for the first time in my life) it down to ES5 by https://esnext.github.io/es6-module-transpiler/. This might be a way to avoid the so called callback hell.
Ãmer KaÅdarma
Related Q & A:
- How do I remove a site from IIS7 using JavaScript?Best solution by Server Fault
- How to implement C callback function in Swift?Best solution by pr8x.com
- How do I avoid the friend zone/not be too much of a nice guy?Best solution by psychologytoday.com
- How do you avoid saggy skin during and after weight loss?Best solution by Yahoo! Answers
- How can I avoid getting tired while I study?Best solution by Yahoo! Answers
Just Added Q & A:
- How many active mobile subscribers are there in China?Best solution by Quora
- How to find the right vacation?Best solution by bookit.com
- How To Make Your Own Primer?Best solution by thekrazycouponlady.com
- How do you get the domain & range?Best solution by ChaCha
- How do you open pop up blockers?Best solution by Yahoo! Answers
For every problem there is a solution! Proved by Solucija.
-
Got an issue and looking for advice?
-
Ask Solucija to search every corner of the Web for help.
-
Get workable solutions and helpful tips in a moment.
Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.