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

时间:2013-01-24 14:45:55

标签: javascript node.js asynchronous callback

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

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

或者您是否需要以下面的回调方式编写它,其中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);
});

我想我有点困惑,关于何时使用异步代码或同步代码。在此先感谢您的帮助。

1 个答案:

答案 0 :(得分:3)

当你所做的只是JavaScript语句时,你不需要设置异步回调。当您的代码处理“真实世界”时,将使用异步API。当您访问IO设备或网络时,会使用异步API,因为活动中存在不可预测的延迟。

如果您正在进行 lot 计算,有一些方法可以设置一个“延续”模型,允许定期中断工作,但这并不是真的相同。

编辑 - 一条评论明智地指出,设计具有异步API的子系统确实没有坏处,即使它不是真的有必要。我还要注意,使用回调进行设计并不是仅针对异步机制进行的。有充分的理由利用JavaScript函数的灵活性作为值。