Reputation: 35
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.
Upvotes: 1
Views: 275
Reputation: 413737
You don't need to set up an asynchronous callback when all you're doing is JavaScript statements. Asynchronous APIs are used when your code is dealing with the "real world". When you access IO devices, or the network, asynchronous APIs are used because there are unpredictable delays inherent in the activities.
If you're doing a lot of computation, there are ways of setting up a "continuation" model that allows for periodic interruption of the work, but that's not really the same thing.
edit — a comment wisely points out that there's really no harm in designing a subsystem with asynchronous APIs even if it's not really necessary. I'll also note that designing with callbacks is not something that's done only for asynchronous mechanisms. There are good reasons to exploit the flexibility of JavaScript functions-as-values.
Upvotes: 3