是否可以在nodejs中使用一些同步代码

我明白,对于I / O操作(即数据库查询,Web请求和磁盘访问),您必须使用这样的callback

fs = require('fs') fs.readFile('test.txt', 'utf8', function (err,data) { if (err) { return console.log(err); } console.log(data); }); 

但是要说你是否有这样的代码同步

 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); 

或者,你需要写在像下面这样的callback风格,calcScore方法只包括一个for循环和一个if语句,不会查询数据库等。

 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); }); 

我想我有点困惑,什么时候使用asynchronous代码或同步代码。 在此先感谢您的帮助。

当你所做的只是JavaScript语句时,不需要设置asynchronouscallback。 当您的代码处理“真实世界”时,会使用asynchronousAPI。 访问IO设备或networking时,会使用asynchronousAPI,因为活动中存在不可预知的延迟。

如果你正在做大量的计算,可以设置一个“连续”模型,以便定期中断工作,但这不是一回事。

编辑 – 一个评论明智地指出,devise一个asynchronousAPI的子系统真的没有坏处,即使它不是真的有必要。 我还会注意到,使用callback进行devise并不是只有asynchronous机制才能完成。 有充分的理由来利用JavaScript函数作为值的灵活性。