NodeJS: the beautiful callback err machine

One of the best things about NodeJS callbacks is their consistency. As in, most API calls require one and their method signature always follows the same pattern, and this is the most beautiful bit.

The first parameter of a callback is always an error object (which is null if no error occurred). This seems a little counterintuative at first. When you stop and think about it though, it really isn’t at all. My initial though was that most of the time, it isn’t going to be used, so why isn’t the result of the computation the first parameter? Well, that might be nice, but chances are you’re actually going to have to check to see if an error occurred first, before you start using your results, since if a error did occur, you probably don’t have any results anyway! Secondly, Node is cleverly reminding you that you should check for and deal with errors as they happen by ensuring you define a first parameter in order to define a second parameter to get at the stuff you want.

If the error was the second (or last) parameter the chances are you’d forget to define it, or the lazy would simply neglect to define it. This could happen because in JavaScript all parameters to functions are optional. Just because you do or don’t define parameters to a function, doesn’t mean you can’t call it with or without parameters. The function might not work in either of these cases, but nevertheless it is still possible to call it. It seems that by not coercing the programmer into defining an error parameter and dealing with it their code could become less robust.

The error parameter in the callback function is a necessity of asynchronous programming because errors cannot usually caught with a try/catch block as the execution of the callback function usually doesn’t happen in the block of code surrounded by the try/catch but instead in a later run of the event loop. I much prefer this way of dealing with errors as opposed to searching through my library code to find out if I even need to surround a function call in a try/catch by figuring out if it even does an operation that could possibly throw an error…and you know what, it’s future proof, because even if a function does no operations that could cause an error, it doesn’t mean that in a future version it won’t. By defining an error parameter from the start you can deal with a future mishap, now that is awesome.

19,657 thoughts on “NodeJS: the beautiful callback err machine

  1. как зайти на сайт кракен – где взять ссылку на кракен https kraken20 at

  2. Fantastic breakdown illustrating differences between various metrics utilized assessing effectiveness performance helping gauge progress accurately informing decisions made going forth dynamically adapting based upon results received continually improving seo company nashville

  3. купить аттестаты об окончании школы

  4. The fact that most warranties last decades when choosing quality materials like steel is encouraging—what warranties have people found most helpful over time? Discuss here or read warranty comparisons on my site: roofing contractors

  5. Testimonials showcasing successful collaborations demonstrate real-world results achieved when working together effectively towards shared goals focusing heavily upon building lasting partnerships among teams involved collectively presented here: TreeStone Security Services

  6. Tormac.org https://tormac.org – это специализированный торрент-трекер предназначенный для пользователей Mac-компьютеров. Сайт предоставляет широкий выбор контента ориентированного на операционные системы macOS и iOS.

  7. Приветствую на https://b2best.at Мы предлагаем надежные и проверенные покупки в интернете. Ознакомьтесь с нашими статьями о безопасности и легальности. Ваши покупки — наш приоритет

  8. Предлагаем услуги профессиональных инженеров офицальной мастерской. Еслли вы искали ремонт iphone 14 рядом можете посмотреть на сайте: ремонт iphone 14 Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом

  9. Предлагаем услуги профессиональных инженеров офицальной мастерской. Еслли вы искали срочный ремонт iphone 14 можете посмотреть на сайте: ремонт iphone 14 рядом Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом

  10. Предлагаем услуги профессиональных инженеров офицальной мастерской. Еслли вы искали ремонт iphone 14 можете посмотреть на сайте: ремонт iphone 14 цены Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом

  11. Предлагаем услуги профессиональных инженеров офицальной мастерской. Еслли вы искали ремонт iphone 14 в москве можете посмотреть на сайте: срочный ремонт iphone 14 Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом

  12. I had the most effective experience at a regional hairdresser recently! The team were so pleasant and specialist. For recommendations, go to mens salon

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>