!!! Listings aus dem Artikel "Gordische Welt" !!! von Sebastian Springer, iX 10/2012, S. 58 !!! Listing 1: package.json { name: backbone, description: Give your JS App some Backbone with Models, Views, Collections, and Events., url: http://backbonejs.org, keywords: [util, functional, server, client, browser], author: Jeremy Ashkenas , contributors: [], dependencies : { underscore: >=1.3.1 }, lib: ., main: backbone.js, version: 0.9.2 } !!! Listing 2: Webserver mit Kindprozess // primeServer.js require('http').createServer(function (req, res) { var startTime = new Date(); console.log('New request incoming'); require('child_process').fork('prime.js').on('message', function (data) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('The 300000st prime number is: ' + data.prime); var timediff = Math.round(((new Date()) - startTime) / 10) / 100; console.log('Request answered in ' + timediff + ' sec'); }); }).listen(1337, '127.0.0.1'); console.log('Server running at http://127.0.0.1:1337'); // prime.js var i, n = 1, results = 1; primeLoop: while (results < 300000) { n += 1; for (i = 2; i <= Math.sqrt(n); i += 1) { if (n % i === 0) { continue primeLoop; } } results += 1; } process.send({'prime': n}); !!! Listing 3: Promise-Beispiel var promise = Q.fcall(function () { if (noError) { return 'successful'; } throw new Error('erroneous'); }); promise.then(function (value) { console.log('Fulfillment: ', value); }, function (reason) { console.log('Rejection: ', reason); }); !!! Listing 4: Promises mit deferred function queryHelper(query) { var deferred = Q.defer(); connection.query(query, function (err, rows, fields) { if (err) { deferred.reject(new Error(err)); } else { deferred.resolve(rows); } }); return deferred.promise; } queryHelper('SELECT * FROM users') .then(function (txt) { console.log(txt); }, function (err) { console.log(err); }); !!! Listing 5: Promise Chaining queryHelper('INSERT INTO data (value) VALUES ("hallo welt")') .the n(function (txt) { return queryHelper('SELECT * FROM data WHERE id = ' + txt.insertId); }) .then(function (txt) { console.log(txt); }); !!! Listing 6: Test mit jasmine-node // src/Calculator.js module.exports = function () {}; module.exports.prototype.add = function (a, b) { return a + b; }; // spec/Calculator.spec.js var Calc = require('../src/Calculator.js'); describe("Calculator", function () { it ("should add 1 and 1 and return 2", function () { var calc = new Calc(); expect(calc.add(1, 1)).toEqual(2); }) });