[async..await Last part]async...await

Calvin Park·2022년 7월 27일
0

callback

목록 보기
3/3

드디어 마지막 파트다. 사실 async..await을 알려고 callback시리즈를 생성하게 된것이다.
왜 callback시리즈를 만들었을까?
Node.js로 개발을 하고 있는데 async...await을 DB에다가 했다.
express프레임워크와 mysql이다.

app.post("/api/customers/insert", async (req, res) => {
  console.log(req.body);
  const result = await mysql.query("customerInsert", req.body);
  res.send(result);

  console.log(error);
});

여기서 궁금증이 생긴것이다. 그래 async와 await는 무엇을 하는지 알겠어 근데, promise도 있다고 들었는데 둘이 정확하게 무슨 차이인걸까? 하다가 근본적인 callback까지 오게 된것이다.

callback 지옥도 봤고 promise.then.catch.finally까지 봤고.
그럼 async에 대해서 더욱더 정확하게 알아보자~!

async await vs promise

async await은 promise에 조금 더 간결하고 간편하고 그리고 동기적!으로 실행되는 것이다.
promise then promise then이렇게 작성하면 코드가 난해질 수도 있다고 생각한다. 하지만
async...await은 promise보다 조금 더 간편하게 쓸수 있다.(syntactic sugar)하지만
promise가 나쁜게 아니라. 어쩔떄는 promise를 쓰는게 더 깔끔하게 나올 수도 있다. 상황에 맞게 쓰는걸 추천한다.

function fetchUser() {
  //do something and it request in 10 secs....
  return "something";
}

const user = fetchUser(); //10초가 지나면서
console.log(user); //출력된다.
//JS는 동기적이기 때문에 한줄 한줄 끊날떄까지 기다린다.
//사용자는 10초 정도 로딩을 기다려야 한다.
//promise를 작성하면

function fetchUser() {
  //언젠간 받아온다고 약속한다잉~~promise 브젝트를 가지고 있으면 여기에 콜백함수만 등록해 놓으면 유저의 데이터가 준비 되는데로 콜백 함수를 불러준다잉~
  return new Promise((resolve, reject) => {
    return "Something";
  });
} 
//상위처럼 작성하면 pending이다. 왜? Resolve 랑 reject가 호출 되지 않았으니깐.pending... pending...
//그럼 이렇게 작성하면
function fetchUser() {
  //언젠간 받아온다고 약속한다잉~~promise 브젝트를 가지고 있으면 여기에 then이랑 콜백함수만 등록해 놓으면 유저의 데이터가 준비 되는데로 콜백 함수를 불러준다잉~
  return new Promise((resolve, reject) => {
    resolve("Something");
  });
}
const user1 = fetchUser();
user.then(console.log);
console.log(user1);
//드디어 된다잉

async await드가자


//await는 async만 붙은 함수안에서만 사용이 가능하다.
function delay(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}
//await을 쓰면 delay가 끝날때까지 기다린다. 그러다가 Apple를 return 하는 함수이다.
async function getApple() {
  await delay(3000);
  return "Apple";
}
//상위와 똑같다.
async function getTomato() {
  await delay(3000);
  return "Tomato";
}
//상위를 promise로 변경 하면
function getTomato() {
  return delay(3000).then(() => "Tomato");
}

function pickFruite() {
  //이렇게 또 callback지옥이 나오게 된다....
  return getApple().then((apple) => {
    return getTomato().then((tomato) => `${apple} + ${tomato}`);
  });
}
pickFruite().then(console.log);


//상위를 async로 변경 드가자~!!
async function pickFruite() {
  const apple = await getApple();
  const tomato = await getTomato();
  return `${apple} + ${tomato}`;
}
pickFruite().then(console.log);

//간단 깔끔 

만약 에러가 발생하면?

async function getApple() {
  await delay(3000);
  // 에러 발생!!
  throw "error";
  return "Apple";
}

async function pickFruite() {
  //try, catch 드가자~
  try {
    const apple = await getApple();
    const tomato = await getTomato();
  } catch (error) {
    console.log(error);
  }
  return `${apple} + ${tomato}`;
}
pickFruite().then(console.log);
//try catch!

useful promise apis 동시다발적으로 실행

function pickAllFruits() {
  //배열 형태로 [getApple(), getTomato()]
  return (
    Promise.all()
      //다받아지면
      //배열을 string으로
      .then((fr4uits) => fruits.join("+"))
  );
}
pickAllFruits().then(console.log());

가장 먼저 값을 리턴한 것만 전달하는거 race()

function pickOnlyOne() {
  //배열에 전달된 promise중에서 가장 먼저 값을 리턴한 function만 전달이 된다. .
  return Promise.race([getApple(), getTomato]);
}

pickAllFruits().then(console.log());

그리고 마지막으로 async await을 실제로 써보았다

const createPost = async (req, res) => {
  const { user, password, title, content } = new Post(req.body);
  if (!user) {
    res.status(400).json({ msg: "이름을 입력해주세요." });
  } else if (!password) {
    res.status(400).json({ msg: "비밀번호 입력해주세요." });
  } else if (!title) {
    res.status(400).json({ msg: "제목 입력해주세요." });
  } else if (!content) {
    res.status(400).json({ msg: "내용 입력해주세요." });
  }
  try {
    //게시글 생성
    await Post.create({ user, password, title, content });
    return res.status(200).json({ msg: "게시글이 생성되었습니다." });
  } catch (error) {
    //오류시
    return res.status(400).json({ msg: "데이터처리 오류" });
  }
};

const getPost = async (req, res) => {
  const { id: postId } = req.params;
  try {
    //게시글 select문
    const post = await Post.findOne({ _id: postId }).select({
      postNumber: 1,
      user: 1,
      title: 1,
      content: 1,
      insDate: 1,
      _id: 1,
    });
    res.status(200).json({ post });
  } catch {
    //게시글이 없으면
    return res.status(400).json({ msg: `${postId}의 글은 없습니다.` });
  }
};

아직 모든 방면에서는 미숙하다. 혹시나 코드에서 문제가 있으면 댓글이나 DM부탁드려욧~!

이렇게 async await인 callback시리즈가 끝났다.

profile
Personal Velog Note

0개의 댓글