Node.js


Asynchronous programming All Versions

v0.5
v0.4
v0.3
v0.2
v0.1
v0.6
v0.7
v0.8
v0.9
v0.10
v0.11
io.js v1.0
io.js v1.1
io.js v1.2
io.js v1.3
io.js v1.4
io.js v1.5
io.js v1.6
io.js v1.7
io.js v1.8
io.js v2.0
io.js v2.1
io.js v2.2
io.js v2.3
io.js v2.4
io.js v2.5
io.js v3.0
io.js v3.1
io.js v3.2
io.js v3.3
v4.0
v4.1
v4.2
v5.0
v5.1
v5.2
v5.3
v5.4
v5.5
v5.6
v4.3
v0.12
v5.7
v4.4
v5.8
v5.9
v5.10
v5.10.1
v5.11.0
v6.0.0
v6.1.0
v5.11.1
v6.2.0
v6.2.1
v6.2.2
v5.12.0
v6.3.0
v6.3.1
v6.4.0
v6.5.0
v6.6.0
v6.7.0
v6.8.0
v6.8.1
v6.9.0
v6.9.1
v7.0.0
v7.1.0
v7.2.0
v6.9.2
v7.2.1
v7.3.0
v7.4.0
v7.5.0

Node is a programming language where everything could run on a asynchronous way. Below you could find some examples and the typical things of asynchronous working.

This draft deletes the entire topic.

Examples

  • 2

    Node works with callback functions. Each callback function will run asyncrounous with other tasks. Here you could find how to make a callback function:

    function doSomething(cb) {
        // do something
    
        // if (error occurred)
            cb(err, null);
    
        // else
            cb(null, data);
    }
    
    doSomething(function(err, data) {
        // This methode will run after `doSomething` is done 
    });
    

    If you don't use asynchronous working, this will be the code:

    function doSomething() {
        try {
            // do something
            return data;
        }
        catch {
            // error handling
            return null;
        }
    }
    
    var data = doSomething();
    
  • 2

    A callback hell (also a pyramid of doom or boomerang effect) arises by to many callback functions in a callback function. Here is an example to read a file (in ES6).

    const fs = require('fs');
    let filename = `${__dirname}/myfile.txt`;
    
    fs.exists(filename, exists => {
        if (exists) {
            fs.stat(filename, (err, stats) => {
                if (err) {
                    throw err;
                }
                if (stats.isFile()) {
                    fs.readFile(filename, null, (err, data) => {
                        if (err) {
                            throw err;
                        }
                        console.log(data);
                    });
                }
                else {
                    throw new Error("This location contains not a file");
                }
            });
        }
        else {
            throw new Error("404: file not found");
        }
    }); 
    

    How could you make this code readable? There is recommended to nest maximum two callback functions. The other callback functions could be named or make use of distributed events.

  • 1

    Try catch

    Errors must always be handled. If you are using synchronous programming you could use a try catch. But this does not work if you work asynchronous! Example:

    try {
        setTimeout(function() {
            throw new Error("I'm a uncaught error and will stop the server!");
        }, 100); 
    }
    catch (ex) {
        console.error("This error will not be work in an asynchronous situation: " + ex);
    }
    

    Async errors will only be handled inside the callback function!

    Working possibilities

    v0.8

    Event handlers

    The first versions of Node.JS got an event handler.

    process.on("UncaughtException", function(err, data) { 
        if (err) {
            // error handling
        }
    });
    
    v0.8

    Domains

    Inside a domain, the errors are release via the event emitters. By using this are all errors, timers, callback methodes implicitly only registrated inside the domain. By an error, be an error event send and didn't crash the application.

    var domain = require("domain");
    var d1 = domain.create();
    var d2 = domain.create();
    
    d1.run(function() {
        d2.add(setTimeout(function() {
            throw new Error("error on the timer of domain 2");
        }, 0));
    });
    
    d1.on("error", function(err) {
        console.log("error at domain 1: " + err);
    });
    
    d2.on("error", function(err) {
        console.log("error at domain 2: " + err);
    });
    
  • 1

    Question: What is the output of code below and why?

    setTimeout(function() {
        console.log("A");
    }, 1000);
    
    setTimeout(function() {
        console.log("B");
    }, 0);
    
    getDataFromDatabase(function(err, data) {
        console.log("C");
        setTimeout(function() {
            console.log("D");
        }, 1000);
    });
    
    console.log("E");
    

    Answer:

    This is known for sure: EBAD. C is unknown when it will be logged.

    Because:

    The compiler will not stop on the setTimeout and the getDataFromDatabase methodes. So the first line he will log is E. The callback functions (first argument of setTimeout) will run after the set timeout on a asynchronous way!

    More details:

    1. E has no setTimeout
    2. B has a set timeout of 0 milliseconds
    3. A has a set timeout of 1000 milliseconds
    4. D must request a database, after it must D wait 1000 milliseconds so it comes after A.
    5. C is unknown because it is unknown when the data of the database is requested. It could be before or after A.

Please consider making a request to improve this example.

Syntax

  • doSomething([args], function([argsCB]) { /* do something when done */});
  • doSomething([args], ([argsCB]) => { /* do something when done */ });

Parameters

Parameters

Remarks

Remarks

Still have a question about Asynchronous programming? Ask Question

Topic Outline