Permalink
Browse files

Optimized to GFM

  • Loading branch information...
1 parent 08dd109 commit 2b314c2bd11ae96b7f41714565515c01a8ef8a66 @pgte pgte committed Aug 10, 2012
Showing with 27 additions and 23 deletions.
  1. +27 −23 article.md
View
@@ -4,35 +4,39 @@ In Node it is considered standard practice to handle errors in asynchronous func
It's simpler than it sounds; let's demonstrate.
- function isTrue (value, callback) {
- if (value === true) {
- callback(null, "Value was true.");
- }
- else {
- callback(new Error("Value is not true!"));
- }
- }
-
- function callback (error, retval) {
- if (error) {
- console.log(error);
- return;
- }
- console.log(retval);
- }
+```javascript
+function isTrue (value, callback) {
+ if (value === true) {
+ callback(null, "Value was true.");
+ }
+ else {
+ callback(new Error("Value is not true!"));
+ }
+}
+
+function callback (error, retval) {
+ if (error) {
+ console.log(error);
+ return;
+ }
+ console.log(retval);
+}
+```
Note: when calling the same asynchronous function twice like this, you are in a race condition.
You have no way of knowing for certain which callback will be called first when calling the functions in this manner.
- isTrue(false, callback);
- isTrue(true, callback);
+```javascript
+isTrue(false, callback);
+isTrue(true, callback);
- { stack: [Getter/Setter],
- arguments: undefined,
- type: undefined,
- message: 'Value is not true!' }
+{ stack: [Getter/Setter],
+ arguments: undefined,
+ type: undefined,
+ message: 'Value is not true!' }
- Value was true.
+ Value was true.
+```
As you can see from the example, the callback is called with null as its first argument if there is no error. However, if there is an error, you create an `Error` object, which then becomes the callback's only parameter.

0 comments on commit 2b314c2

Please sign in to comment.