빠른 참조

co 제너레이터 비동기 흐름 제어 치트시트

Node.js용 제너레이터 기반 비동기 제어 라이브러리 co 퀵 레퍼런스: 실행, co.wrap, thunk 함수 연동, 프로미스 변환 및 병렬 처리.

· 게시일

co co는 최신 JavaScript의 async/await 문법의 기반이 된 제너레이터(Generator) 기반 클래식 비동기 제어 흐름 라이브러리입니다.

제너레이터 실행

const co = require('co');

co(function* () {
  const result = yield Promise.resolve(42);
  return result * 2;
}).then(val => {
  console.log(val); // 84
}).catch(err => {
  console.error(err);
});

제너레이터 함수 내에서 Promise, thunk, 배열, 객체를 yield 할 수 있습니다. co()는 제너레이터를 끝까지 자동 실행합니다.


재사용 가능한 프로미스 함수로 변환 (co.wrap)

제너레이터를 일반 Promise를 반환하는 표준 함수로 래핑합니다 (최신 async function과 완벽히 동일):

const getUser = co.wrap(function* (id) {
  const user = yield db.users.findById(id);
  const posts = yield db.posts.findByUser(user.id);
  return { user, posts };
});

// 호출 시 표준 Promise 반환:
getUser(123).then(data => {
  console.log(data);
});

Node.js 콜백 스타일 API 연동

thunkify 또는 프로미스화 래퍼를 활용한 콜백 처리:

const thunkify = require('thunkify');
const fs = require('fs');

const readFile = thunkify(fs.readFile);

co(function* () {
  const content = yield readFile('config.json', 'utf8');
  console.log(JSON.parse(content));
});

병렬 실행 (배열 및 객체)

co(function* () {
  // 배열 내부 비동기 작업 병렬 처리
  const [user, profile] = yield [fetchUser(), fetchProfile()];

  // 객체 프로퍼티 비동기 작업 병렬 처리
  const data = yield {
    user: fetchUser(),
    profile: fetchProfile()
  };
  console.log(data.user, data.profile);
});

관련 주제