Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

added

  • Loading branch information...
commit a4543423f226010229a7da55c32998c1756d329f 0 parents
Paolo Fragomeni authored

Showing 3 changed files with 88 additions and 0 deletions. Show diff stats Hide diff stats

  1. +8 0 article.json
  2. +79 0 article.md
  3. +1 0  example.file
8 article.json
... ... @@ -0,0 +1,8 @@
  1 +{
  2 + "title":"Writing asynchronous code",
  3 + "description": "Nodejs promotes an asynchronous coding style from the ground up, in contrast to many of the most popular web frameworks."
  4 + "date": "Fri Aug 26 2011 03:08:50 GMT-0700 (PST)",
  5 + "tags": ["asynchronous", "callbacks", "event-emitters"],
  6 + "authors": ["Nico Reed"],
  7 + "difficulty": 1
  8 +}
79 article.md
Source Rendered
... ... @@ -0,0 +1,79 @@
  1 +Nodejs promotes an asynchronous coding style from the ground up, in contrast to many of the most popular web frameworks. There are a number of important things to be aware of when learning to write asynchronous code - otherwise, you will often find your code executing in extremely unexpected ways. Take this (general) rule to heart:
  2 +
  3 +### Use the asynchronous functions, avoid the synchronous ones!
  4 +
  5 +Many of the functions in Node.js core have both synchronous and asynchronous versions. Under most circumstances, it will be far better for you to use the asynchronous functions - otherwise, why are you using Node.js?
  6 +
  7 +As a quick example comparing and contrasting the two, using `fs.readFile`:
  8 +
  9 +```js
  10 +var fs = require('fs');
  11 +
  12 +fs.readFile('example.file', 'utf8', function (err, data) {
  13 + if (err) {
  14 + return console.log(err);
  15 + }
  16 + console.log(data);
  17 +});
  18 +
  19 +//====================
  20 +
  21 +var data = fs.readFileSync('example.file','utf8');
  22 +console.log(data);
  23 +```
  24 +
  25 +Just looking at these two blocks of code, the synchronous version appears to be more concise. However, the asynchronous version is more complicated for a very good reason. In the synchronous version, the world is paused until the file is finished reading - your process will just sit there, waiting for the OS (which handles all file system tasks).
  26 +
  27 +The asynchronous version, on the other hand, does not stop time - instead, the callback function gets called when the file is finished reading. This leaves your process free to execute other code in the meantime.
  28 +
  29 +When only reading a file or two, or saving something quickly, the difference between synchronous and asynchronous file I/O can be quite small. On the other hand, though, when you have multiple requests coming in per second that require file or database IO, trying to do that IO synchronously would be quite thoroughly disastrous for performance.
  30 +
  31 +
  32 +###Callbacks
  33 +Callbacks are a basic idiom in node.js for asynchronous operations. When most people talk about callbacks, they mean the a fuction that is passed as the last parameter to an asynchronous function. The callback is then later called with any return value or error message that the function produced. For more details, see the article on [callbacks](/articles/getting-started/control-flow/what-are-callbacks)
  34 +
  35 +###Event Emitters
  36 +Event Emitters are another basic idiom in node.js. A constructor is provided in Node.js core: `require('events').EventEmitter`. An Event Emitter is typically used when there will be multiple parts to the response (since usually you only want to call a callback once). For more details, see the article on [EventEmitters](/articles/getting-started/control-flow/what-are-event-emitters)
  37 +
  38 +###A gotcha with asynchronous code
  39 +A common mistake in asynchronous code with javascript is to write code that does something like this:
  40 +
  41 +```js
  42 +for (var i = 0; i < 5; i++) {
  43 + setTimeout(function () {
  44 + console.log(i);
  45 + }, i);
  46 +}
  47 +```
  48 +
  49 +The unexpected output is then:
  50 +
  51 +```
  52 + 5
  53 + 5
  54 + 5
  55 + 5
  56 + 5
  57 +```
  58 +
  59 +The reason this happens is because each timeout is created and then `i` is incremented. Then when the callback is called, it looks for the value of `i` and it is 5. The solution is to create a closure so that the current value of `i` is stored. For example:
  60 +
  61 +```
  62 +for (var i = 0; i < 5; i++) {
  63 + (function(i) {
  64 + setTimeout(function () {
  65 + console.log(i);
  66 + }, i);
  67 + })(i);
  68 +}
  69 +```
  70 +
  71 +This gives the proper output:
  72 +
  73 +```
  74 + 0
  75 + 1
  76 + 2
  77 + 3
  78 + 4
  79 +```
1  example.file
... ... @@ -0,0 +1 @@
  1 +Hello, World

0 comments on commit a454342

Please sign in to comment.
Something went wrong with that request. Please try again.