Receiving the error “done is not a function.” Yes, I did google and see similar forum posts. I am fairly sure I am passing done correctly to my function (which was the issue in the posts), although that may not be the case. Forked repl.lit for editing here.
Relevant code:
var shortURLNumber = 0;
function createAndSaveURL(htmlInput, done) {
shortURLNumber++;
console.log("In create and save, shortURLNumber is "+shortURLNumber);
const shortURLhere = ('/api/shorturl/' + shortURLNumber);
var urlToSave = NewURL({long: htmlInput, short: shortURLhere});
urlToSave.save (function(err, data) {
if (err) {return console.error(err)};
done(null, data); //this is the line throwing an error according to the console
});
};
Shameless self-reply to bump this. Yes, createAndSaveURL needs two arguments and I was only passing one. But if I pass “done” or “done=Function” as the second, I still get errors, specifically the same error or “done is not defined.” Anybody?
Thank you for the reply. And yes, the code above does not pass the second argument. But if I pass “done” or “done=Function” as a second argument, i.e.,
createAndSaveURL(req.body["url"], done);
or
createAndSaveURL(req.body["url"], done=Function);
I get errors as stated above. So I guess I am not passing done correctly but I am unclear as to how to do this properly?
Regarding defining done, I was basically copying the structure from the Mongoose challenges. (Forked here.) As near as I can tell, done is never defined, but it just … works. Which is perplexing to me.
As to why, my understanding was that it was good practice to have some sort of error-catching callback, although I would guess that having a done function is not the only way to go about that.
freeCodeCamp has already defined done. So, you can find it in the boilerplate. I am AFK, so cannot find it right now. Just look for any argument passed to one of the imported functions from myApp.js. Probably in server.js but this is off the top of my head.
Generally, it is good practice. By all means, keep it up. However, I have only ever come across one situation where I actually used such a style. Ideally, it is used for correct error handling. So, quite important in production apps, but for small-scale projects, mostly unnecessary.
Thank you, I noticed the function in there seemed to resolve the done function’s ability but I was/am still a little unclear on anonymously defined functions. (Will Google/read.) I assume the renaming of createPerson is so that there is a separate function for FCC to edit and it doesn’t clash with the camper’s createAndSavePerson funciont. But I will not ask why.
Anyway, thank you again for the multiple replies and clarifications, they are very helpful.