Can someone explain 'done'?

var createAndSavePerson = function(done) {
  var person = new Person({ 
    name: 'Bob', 
    age: 64, 
    favoriteFoods: ["icecream", "pasta"] 
  });  
  
  person.save(function(err, data) {
    if (err) return done(err);
    return done(null,data);
  });
 };

Can someone explain what done is doing here?
And if createAndSavePerson is declared as a function, why is it never called so that it actually runs, i.e. createAndSavePerson()

Well, I think I can answer the first question. ‘Done’ represents your callback function that you would pass in to createAndSavePerson. That callback function determines how your error or data gets handled.

So, perhaps in one part of your code, you call createAndSavePerson and just want to log whatever comes back to the console. So you pass it a function to do just that, like so:

createAndSavePerson(function(err, data) {
  if (err) {
    console.log(err);
  } else if (data) {
    console.log(data);
  }
});

But then maybe in another part of your code where you call createAndSavePerson you want something more serious to happen with data, like have it be saved to a database. In that case, you’d pass it a different callback function, one that saves stuff to the db.

1 Like

createAndSavePerson() is never called because FCC test suite calls this function to see if you’ve implement it correctly.
And done is a callback just what Artem explained above.

1 Like

is this also a function passed into person.save()

function(err, data) { 
  if (err) return done(err); 
    return done(null,data); 
}

so done() is being called inside an anonymous function?

Yep, that’s right. And that anonymous function knows what done is because it looks up the scope chain and finds it inside createAndSavePerson.

1 Like

Thank you… think I’m finally getting this :laughing: