简体   繁体   English

Node.js中的函数(err)回调

[英]function (err) callback in Node.js

I'm still trying to wrap my head around what are function callback and how it works. 我仍在尝试着围绕什么是函数回调及其工作原理。 I understand that it is a vital part of javascript. 我了解这是javascript的重要组成部分。 For example this method writeFile from node.js documentation, what does this function callback do? 例如,来自node.js文档的writeFile方法,此函数回调做什么? How can this function have an input for err ? 此函数如何为err输入?

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

fs.writeFile will pass an error to your callback function as err in the event an error happens. fs.writeFile发生errorfs.writeFile会将error作为err传递给回调函数。

Consider this example 考虑这个例子

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 seconds later ... 2秒后...

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

In the example above, wakeUpSnorlax is like fs.writeFile in that it takes a callback function to be called when fs.writeFile is done. 在上面的示例中, wakeUpSnorlax类似于fs.writeFile ,因为它完成fs.writeFile后需要调用一个回调函数。 If fs.writeFile detects and error during any of its execution, it can send an Error to the callback function. 如果fs.writeFile在执行任何过程中检测到错误,则可以将Error发送给回调函数。 If it runs without any problem, it will call the callback without an error. 如果运行没有问题,它将无错误地调用回调。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM