Node.js中的函数(err)callback

我仍然试图围绕什么是函数callback以及它是如何工作的。 我知道这是JavaScript的重要组成部分。 比如这个方法从node.js文件中写入文件,这个函数的callback是做什么的? 这个函数怎么能为errinput?

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

fs.writeFile发生errorfs.writeFile会将error传递给您的callback函数。

考虑这个例子

 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! 

在上面的例子中, wakeUpSnorlax就像fs.writeFile ,它在fs.writeFile完成时需要调用一个callback函数。 如果fs.writeFile在其执行过程中检测到错误,并且可以向callback函数发送Error 。 如果它运行没有任何问题,它会调用callback没有错误。