All About CRUD - Promise (Async/Await)

Jun's Coding Journey·2022년 11월 12일
0

[Challenge] Youtube Clone

목록 보기
11/19

Promise with Async/Await

A promise is a JavaScript object that represents either the eventual completion or failure of an asynchronous operation and its resulting value. Normally, a promise uses a callback to handle the results of a function fulfilling a value or producing an error. Depending on the process, a promise can either be fulfilled, rejected, or pending.

export const home = (req, res) => {
  Video.find({}, (error, videos) => {
    return res.render("home", { pageTitle: "Home", videos });
  });
};

Before the use of promise, we had to always have callback parameters for the function to interact with the database. However, this became easier with async and await functionalities.

As the name says, using the async keyword on a function makes that particular function into an asynchronous function. This allows us to write promises based code as if it was synchonous and it check that we are not breaking the execution thread. Async functions will always return a value (whether it may be a value or an error).

Await function is used to wait for the promise to happen. This makes the code wait until the promise returns a result.

With these two functions, the code gets executed line-by-line which makes it very easier to look at. Additionally, we do not need to have callbacks.

export const home = async (req, res) => {
  const videos = await Video.find({});
  return res.render("home", { pageTitle: "Home", videos });
};

If we want to also see the error results of a promise function, we can use the try and catch functions. These functions can catch and display errors in case there is no value to return.

export const home = async (req, res) => {
  try {
    const videos = await Video.find({});
    return res.render("home", { pageTitle: "Home", videos });
  } catch {
    return res.render("server-error");
};
profile
Greatness From Small Beginnings

0개의 댓글