I understand that for I/O operations(ie database queries, web requests and disk access) you must use callbacks like this
fs = require('fs')
fs.readFile('test.txt', 'utf8', function (err,data) {
if (err) {
return console.log(err);
}
console.log(data);
});
but say if you have synchronize code like this
function Player(name){
this.name = name;
this.score = 0;
}
Player.prototype.calcScore = function(){
//some special code here to calculate the score
this.score =+ 10;
}
var player = new Player("Sam");
player.calcScore();
console.log(player);
Or do you need to write it in a callback style like below where the calcScore method only includes maybe a for loop and an if statement and does not query databases etc.
function Player(name){
this.name = name;
this.score = 0;
}
Player.prototype.setScore = function(data){
this.score = data
}
Player.prototype.calcScore = function(callback){
//some special code here to calculate the score
var newscore = this.score += 10;
callback(null, newscore);
}
var player = new Player("Sam");
player.calcScore(function(err, data){
if(err){
return console.log(err);
}
player.setScore(data);
console.log(player);
});
I guess I am a bit confused and about when to use async code or sync code. Thanks in advance for your help.