Callback is a function which runs after certain action is executed. Just like EventListener:
btn.addEventListener("click", callbackFunction);
callback function inside the eventlistener executed only after "click" action is executed.
app.listen(PORT, handleListening)
can be a form of callback function too.
***Easy way to understand - You want your guests to be at the dinner table when the dinner is all ready and not while you making it.
import Video from "../models/Video"
export const home = (req, res) => {
Video.find({}, (error, documents) => {
});
//This calls Video model when home URL is requested. or give info about the error and documents if error occurs.
};
But when you run the callback, it finishes last. What it mean by 'finishing last' is that:
import Video from "../models/Video"
export const home = (req, res) => {
console.log("Start");
Video.find({}, (error, documents) => {
console.log("Searching");
});
console.log("End");
return res.render("home", {pageTitle: "home", videos: [] });
};
Start
-> Searching
-> End
.Start
-> End
-> Searching
.async await is a promise. Consider it as a better version of callback function. Simpler than callback function,
export const home = async (req, res) => {
const video = await Video.find({});
};
export const home = async (req, res) => {
try{
const video = await Video.find({});
return res.render("home", {pageTitle: "Home", videos: []});
}catch(error){
return res.render("Error: ", {error});
}
};