dazer
dazer

Reputation: 223

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. For example this method writeFile from node.js documentation, what does this function callback do? How can this function have an input for err?

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

Upvotes: 1

Views: 9892

Answers (1)

Mulan
Mulan

Reputation: 135217

fs.writeFile will pass an error to your callback function as err in the event an error happens.

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 ...

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. If fs.writeFile detects and error during any of its execution, it can send an Error to the callback function. If it runs without any problem, it will call the callback without an error.

Upvotes: 10

Related Questions