Asynchronous programming All Versions
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
-
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();
-
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.
-
-
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.8Event handlers
The first versions of Node.JS got an event handler.
process.on("UncaughtException", function(err, data) { if (err) { // error handling } });
v0.8Domains
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); });
-
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 thegetDataFromDatabase
methodes. So the first line he will log isE
. The callback functions (first argument ofsetTimeout
) will run after the set timeout on a asynchronous way!More details:
1.
E
has nosetTimeout
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 mustD
wait 1000 milliseconds so it comes afterA
.
5.C
is unknown because it is unknown when the data of the database is requested. It could be before or afterA
.
Syntax
- doSomething([args], function([argsCB]) { /* do something when done */});
- doSomething([args], ([argsCB]) => { /* do something when done */ });
Sign up or log in
Save edit as a guest
Join Stack Overflow
Using Google
Using Facebook
Using Email and Password
We recognize you from another Stack Exchange Network site!
Join and Save Draft