Callback and promise(Async await)

PussinSocks·2022년 7월 22일
0

CloneCoding

목록 보기
13/20

Callback

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.

  • Calling the database is same in the controller.
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: [] });
};
  • Theoretically, the the console should go from Start-> Searching-> End.
    However, when you actually request the URL, the order of the console will be Start -> End -> Searching.
  • It gets convient because we don't want to render the browser before the data is not searched.
  • But there's even more efficient way to write a code compare to the above (The one on the above has function inside of function and it is not considered as a good coding).
  • That is async await

Async await

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({});
};
  • But what about the error? => Try and Catch syntax
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});
  }
};
  • await wait for database to be loaded
profile
On a journey to be a front-end developer

0개의 댓글