Note that there are some explanatory texts on larger screens.

plurals
  1. POIn node.js programming, how do you handle the scenario where a callback doesn't fire?
    primarykey
    data
    text
    <p>A frequently used asynchronous function call idiom in node.js is to use callback functions like this:</p> <pre><code>library.doSomething(params, function(err,result) { if (err) { ... handle error, retry etc } else { ... process results, be happy! } }); </code></pre> <p>It's great - you call something, then later on handle the results or an error. There is unfortunately an excluded third option... that the code you've called never executes your callback. What are the best approaches to handle the possibility of a callback never getting called?</p> <p>A lot of the time, especially if you're writing a library that relies on the network, you need to guarantee that you will call any callbacks passed to you once and only once. With that in mind, a pattern something like this looks like the way to go:</p> <pre><code>// set a timout var failed = false, callbackFailure = setTimeout(function() { ... handle failure, call further pending callbacks with a timeout error failed = true; },30000); library.doSomething(params, function(err,result) { if (!failed) { clearTimeout(callbackFailure); if (err) { ... handle error, retry etc } else { ... process results, be happy again! } } }); </code></pre> <p>It seems like a matter of faith that any callback you expect to fire actually will fire, and I'm sure all programmers have run into scenarios where callbacks simply won't execute for whatever reason - cosmic rays, sunspots, network failures, bugs in a third party library, or ... <em>gasp</em> ... bugs in your own code.</p> <p>Is something like my code example actually a good practice to adopt or has the node.js community already found a better way to handle it?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload