1

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.

4

1 に答える 1

3

JavaScriptステートメントだけを実行している場合は、非同期コールバックを設定する必要はありません。非同期APIは、コードが「現実の世界」を処理しているときに使用されます。IOデバイスまたはネットワークにアクセスする場合、アクティビティに固有の予測できない遅延があるため、非同期APIが使用されます。

多くの計算を行う場合、作業の定期的な中断を可能にする「継続」モデルを設定する方法がありますが、それは実際には同じことではありません。

編集—コメントは、非同期APIを使用してサブシステムを設計することは、実際には必要ではない場合でも、実際には害がないことを賢明に指摘しています。また、コールバックを使用した設計は、非同期メカニズムに対してのみ行われるものではないことにも注意してください。JavaScriptの値としての関数の柔軟性を活用するのには十分な理由があります。

于 2013-01-24T14:48:54.460 に答える