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

daz*_*zer 1 javascript callback node.js

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

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

Tha*_*you 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); 
Run Code Online (Sandbox Code Playgroud)

2秒后......

the snorlax did not wake up!
the snorlax did not wake up!
the snorlax woke up!
Run Code Online (Sandbox Code Playgroud)

在上面的例子中,wakeUpSnorlax就像fs.writeFile在fs.writeFile完成时需要调用一个回调函数.如果fs.writeFile在任何执行期间检测到并发生错误,它可以发送Error回调函数.如果它运行没有任何问题,它将调用回调而没有错误.