Last active
August 29, 2015 14:15
-
-
Save JBarna/5e172b4a6f2161ea6c35 to your computer and use it in GitHub Desktop.
Example of Asynchronous Nature of Node.js JavaScript
This file contains hidden or 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
/** | |
* Even though javascript doesn't have types, there are many | |
* languages that people have built which complie to legitemate JS. | |
* Check out TypeScript at http://www.typescriptlang.org/ | |
* For more information*/ | |
/** | |
* The output of this file is as follows: | |
- Before myFun | |
- Value is : 6 | |
- After myFun | |
- Value is : 7 | |
*/ | |
var myFun = function(value, cb){ | |
value += 1; //value = 6 | |
process.nextTick(function(){ //nextTick -> place this function at the end of the event queue | |
value += 1; //value = 7 but only when this function runs | |
cb(value); | |
}); | |
cb(value); //immediately (synchronosly) call the callback, value still = 6 | |
}; | |
var callback = function(value){ | |
console.log("Value is : " + value); | |
}; | |
//main | |
function main(){ | |
console.log("Before myFun"); | |
myFun(5, callback); | |
console.log("After myFun"); | |
} | |
main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment