javascript - How is this asynchronous? -


i'm new node.js , asynchronous js , i'm not sure if interpret correctly. i'm trying understand how chunk of code:

var fs = require('fs') var filedir = process.argv[2]  function donereading(err, filecontents) {     var lines = filecontents.split("\n")     console.log(lines.length-1) } function countlines(filedir) {     fs.readfile(filedir, "utf8", donereading) } countlines(filedir) 

is asynchronous? because can call countlines function multiple times, each time different filedir argument, prints out length of file? mean.. how asynchronous? isn't how functions work?

it asynchronous. not asynchronous because called countlines() multiple times. asynchronous because did asynchronous function call at:
fs.readfile(filedir, "utf8", donereading);

this function not going block process. called asynchronously. after call function, control not wait function finish synchronously continues remaining code. when file loaded, callback function called. put console.log("i run first") after countlines() function call , feed large file script. can see console logs i run first before file content loaded. if use fs.readfilesync() synchronous alternative, , put console.log() , log after function call, see script waits till whole file read , logs log.

asynchronous functions have pattern:

yourasynccall(arg1,arg2,...,callbackfunction); 

you see callbackfunction() can implicitly defined anonymous function in oliver's answer or defined somewhere else example. has convention of error first argument , result callback(if no error occurs) second argument. can see in

function donereading(err, filecontents); 

Comments

Popular posts from this blog

php - Zend Framework / Skeleton-Application / Composer install issue -

c# - Better 64-bit byte array hash -

python - PyCharm Type error Message -