Skip to content

Instantly share code, notes, and snippets.

@jpanganiban
Created November 24, 2012 17:04
Show Gist options
  • Save jpanganiban/4140530 to your computer and use it in GitHub Desktop.
Save jpanganiban/4140530 to your computer and use it in GitHub Desktop.
A short demonstration on asynchronous processing with node.
/*
* A short demonstration on asynchronous processing with node.
*/
// Asynchronous adding method
var add = function(a, b, timeout, callback) {
setTimeout(function() {
callback(a + b);
}, timeout * 1000); // Sleeps for <timeout> miliseconds.
};
// Asynchronous subtracting method
var subtract = function(a, b, timeout, callback) {
setTimeout(function() {
callback(a - b);
}, timeout * 1000); // Sleeps for <timout> miliseconds.
};
addThenSubtract = function(a, b, c, callback) {
// Add a and b
console.log('start adding');
add(a, b, 1, function(res) {
console.log("result for adding: " + res);
});
console.log('start subtracting');
// Subtract b and c
subtract(b, c, 1, function(res) {
console.log("result for subtractor: " + res);
});
console.log('next process');
};
addThenSubtract(1,3,2);
/*
* What you normally expect from synchronous process:
* start adding
* result for adding: 4
* start subtracting
* result for subtracting: 1
* next process
*
* What actually happens:
* start adding
* start subtracting
* next process // You will notice that it didn't wait
* result for adding: 4 // for the long process to finsh. Instead,
* result for subtracting: 1 // it went on with the next line of code).
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment