상현에 하루하루
개발자의 하루

async & await 코드스피츠 88 실습

( 업데이트: )

실무에서 사용할 만한 예제를 보여주시는데 이 것을 리액트에서 똑같이 한 번 실습해보고 싶었다.

Client

CRA를 통해서 제작한 App.js에서

import React from "react";
import logo from "./logo.svg";
import "./App.css";

const api2 = async (url, timeout = 50000, info = {}) => {
  let id = -1;
  const v = await Promise.race([
    new Promise((res) => (id = window.setTimeout((_) => res(), timeout))),
    fetch(new Request(url, info)),
  ]);
  if (v instanceof Response) {
    clearTimeout(id);
    if (v.status === 404) throw new Error("404");
    return await v.json();
  } else throw new Error("timeout");
};

const infinity = async function* (cat) {
  let page = -1;
  do {
    try {
      const { nextPage, items } = await api2(
        `http://localhost:8080/list/${cat}/${page === -1 ? "" : page}`
      );
      page = nextPage;
      yield items;
    } catch (error) {
      return;
    }
  } while (page !== -1);
};
const notice = infinity("notice");
(async () => {
  const { value, done } = await notice.next();
  if (!done) console.log(value);
})();

function App() {
  const hendleClick = async () => {
    const { value, done } = await notice.next();
    if (!done) console.log(value);
    else console.log(value, done);
  };
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
        <ul></ul>
        <button onClick={hendleClick}>lead more</button>
      </header>
    </div>
  );
}

export default App;
Code language: JavaScript (javascript)

Server

express를 통한 간단한 api 구성

const express = require("express");
// const path = require('path');
const router = express.Router();

router.all("/*", (req, res, next) => {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  next();
});
router.get("/", (req, res, next) => {
  res.write("Hello World!..."); //write a response to the client
  res.end(); //end the response
});
router.get("/list/notice", (req, res, next) => {
  const result = {
    nextPage: 1,
    items: { id: 0 },
  };
  res.json(result);
});
router.get("/list/notice/:id", (req, res, next) => {
  const id = req.params.id;
  const result = {
    nextPage: id === 100 ? -1 : new Number(id) + 1,
    items: { id: new Number(id) },
  };

  res.json(result);
});

module.exports = router;Code language: PHP (php)

후기

asyncPromise를 반환한다. 이 것을 분명히 명심하고있고 Promise 에 대해서 명확하게 알고있다면 흐름을 잘 찾아 갈 수 있다. 이 강의를 지금 현재는 2번씩 들었더니 이전에 두개가 분리되어 이해하고있던 개념이 Promise를 콜백지옥에서 해결? 해줄수있고 코드를 읽는데 좀더 코드가 널뛰기해서 해석하는데 어렵던 점이 CPS라는 패턴으로 조금더 쉽게 이해할 수 있게 되었다.

앞으로 계속 틈날때 한 번씩 보면서 개념을 이해하고 간단한 예제와 앞으로 function을 promise return으로 만들어서 구현하면서 익숙해져야 할 것같다.