Created
November 24, 2012 17:04
-
-
Save jpanganiban/4140530 to your computer and use it in GitHub Desktop.
A short demonstration on asynchronous processing with node.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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