ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • CRUD 연습 중에 발견한 async, await 용도
    기타 공부 2022. 5. 22. 04:50
    const { Router } = require("express");
    const { Snack } = require("../models");
    
    const router = Router();
    
    // 새로운 과자를 추가하는 API를 만드세요.
    router.post('/', async (req, res) => {
        // 과자의 name, price, company를 body를 통해 전달받음
        const { name, price, company } = req.body;
        // DB에 동일한 name이 존재하는 경우 에러 메시지를 반환
        const snackExists = await Snack.findOne({name})
         if (snackExists){
             return res.status(400).json({
          status: "Error",
          error: "이미 존재하는 과자 이름입니다.",
         });
        }
        // DB에 동일한 name이 존재하지 않는 경우 새로운 과자를 DB에 삽입.
        const snack = await Snack.create({
            name,
            price,
            company,
        })
        res.json(snack)
    })
    router.get("/", (req, res) => {
      res.render("snack");
    });
    
    module.exports = router;

    과자의 name, price, company를 입력하는데, 데이터베이스에 벌써 같은 이름을 가진 과자가 있다면 "이미 존재하는 과자 이름입니다." 라며 오류를 뱉어야 정상이다.

    처음에는 이런 코드를 썼었다.

    router.post('/', async (req, res) => {
        const { name, price, company } = req.body;
         if (Snack.findOne({name})){
             return res.status(400).json({
          status: "Error",
          error: "이미 존재하는 과자 이름입니다.",
         });
        }
        const snack = await Snack.create({
            name,
            price,
            company,
        })
        res.json(snack)

    Snack.findOne({name}) 을 await 해준 후 그것을 변수로 넘겨주어야 하는데, 그러지 않은 것이였다.

    아직 async/await 사용이 익숙치 않아서 생긴 일인데, 이렇게 하니까 처음 등록하는 과자조차 "이미 존재하는 .."이라면서 오류를 뱉었다. 당연하지만 DB에 추가도 되지 않았다.

    await을 시켜주니 정상적으로 snack은 exists하지 않았고, 정상적으로 추가가 되었다. 앞으로 비슷한 문제가 발생할시 이런 기초적이지만 중요한 개념에 대해서 체크하는 버릇이 생길 것 같다.

    댓글

Designed by Tistory.