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.

20,896 thoughts on “NodeJS: the beautiful callback err machine

  1. Thanks for highlighting the role of social media in truly property advertising and marketing—or not it’s such an victorious tool lately to connect with doable clients or renters—be informed more processes from our website Savvy Fox Buyers Agent

  2. Внимание игроки Готовы окунуться в мир виртуальных-казино и выиграть реальные средства? Тогда вам сюда Топ самых превосходных игровых сайтов 2025 Наш телеграм-аккаунт — ваш проводник в окружение превосходных онлайн-казино в Российской Федерации Мы подобрали топ-10 безопасных игровых площадок где вы получите возможность развлекаться на средства и забрать свои призы без проблем. Что вас ожидает: Достоверные отзывы и ранги рус казино от реальных геймеров. Хорошая репутация каждого сайта проверена опытом и игроками. Бесплатная регистрация и быстрый вход на любой сайтах. Рабочие дубликаты для входа к вашему предпочитаемому казино в любой час. Мобильный программа для легкой игры где желаете. Почему нам? Надежные и проверенные игровые площадки с лучшими условиями для проведения времени. Защита ваших сведений и переводов обеспечена. Новые обновления и новости окружения онлайн-казино в Российской Федерации.

  3. Он отметил что ГУ «Городская реклама и инфа» создано задавшись целью упорядочения рекламно-информационной работы в области размещения внешней рекламы на объекте благоустройства зданий конструкций и меховых объектах расположенных в руках города http://stroyles.by/index.php?option=com_k2&view=item&id=5-up и является подведомственным учреждением Комитета по штампы и взаимодействию со СМИ.

  4. hey there and thank you for your info – I’ve certainly picked up something
    new from right here. I did however expertise some technical points using this web site, as I
    experienced to reload the site lots of times previous to I could get it to load properly.
    I had been wondering if your hosting is OK? Not that I’m
    complaining, but sluggish loading instances times will sometimes affect your placement in google and could damage your high-quality score if ads and marketing with Adwords.
    Anyway I’m adding this RSS to my e-mail and can look out for
    much more of your respective intriguing content.
    Ensure that you update this again very soon.

    Feel free to visit my blog – zaramea01

  5. id=”firstHeading” class=”firstHeading mw-first-heading”>Search
    results

    Help

    English

    Tools

    Tools
    move to sidebar hide

    Actions

    General

  6. Good day! This is my 1st comment here so I just wanted to give a quick shout out and say I genuinely enjoy reading your blog posts.
    Can you suggest any other blogs/websites/forums
    that go over the same topics? Thank you so much!

    Feel free to surf to my web-site zaramea01

  7. http://umalutki.ru/ — Качественные кухни и удобный интерфейс для оформления заказа онлайн.

  8. Szybka sprzedaż nieruchomości to idealna opcja w sytuacjach wymagających szybkiego pozbycia się mieszkania lub domu. Dzięki temu procesowi można uniknąć długotrwałych negocjacji i formalności wycena nieruchomości

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>