I'd write the following code to practice function with callback in javascript.
fs = require('fs');
function funcWithCallback(callback) {
fs.readFile('YouBikeTP.txt', 'utf8', function (err,data) {
if (err) {
return console.log(err);
}
console.log(data.length);
});
callback();
}
funcWithCallback(function(){
console.log("string in callback ")
})
The purpose of the code is try to control the sequence of methods execution. The string "string in callback" should be printed after the length of text file be printed, but when I ran this code the result will be:
>> "string in callback"
>> 91389 //the length of YouBikeTP.txt
which is not the result I expected. should be
>> 91389 //the length of YouBikeTP.txt
>> "string in callback"
could anyone tell me why will the callback function been called before funcWithCallback(callback) complete ? Did I misunderstand the meaning of callback function ?