Node.js中的函数(错误)回调

时间:2013-08-30 01:31:35

标签: javascript node.js callback

我仍然试图围绕什么是函数回调以及它是如何工作的。我知道它是javascript的重要组成部分。例如这个方法来自node.js文档的writeFile,这个函数回调做了什么?该函数如何为err输入?

fs.writeFile('message.txt', 'Hello Node', function (err) {
  if (err) throw err;
console.log('It\'s saved!');
});

1 个答案:

答案 0 :(得分:10)

如果发生错误,

fs.writeFile会将error传递给您的回调函数err

考虑这个例子

function wakeUpSnorlax(done) {

  // simulate this operation taking a while
  var delay = 2000;

  setTimeout(function() {

    // 50% chance for unsuccessful wakeup
    if (Math.round(Math.random()) === 0) {

      // callback with an error
      return done(new Error("the snorlax did not wake up!"));
    }

    // callback without an error
    done(null);        
  }, delay);
}

// reusable callback
function callback(err) {
  if (err) {
    console.log(err.message);
  }
  else {
    console.log("the snorlax woke up!");
  }
}

wakeUpSnorlax(callback); 
wakeUpSnorlax(callback); 
wakeUpSnorlax(callback); 

2秒后......

the snorlax did not wake up!
the snorlax did not wake up!
the snorlax woke up!

在上面的示例中,wakeUpSnorlaxfs.writeFile类似,因为它在fs.writeFile完成时需要调用回调函数。如果fs.writeFile在任何执行期间检测到并发生错误,则可以向回调函数发送Error。如果它运行没有任何问题,它将调用回调而没有错误。