[Node.js]Promise와 Generator


ECMAScript 2015에서는 콜백 지옥을 피하고자 Promise와 Generator라는 기능이 추가되었습니다. 이를 이용하면 비동기처리를 쉽게 할 수 있습니다.


Promise

프로미스는 비동기 처리로 구한 실제 값을 반환하지 않고, 일단 Promise 객체를 반환한 뒤, 처리가 완료되는 시점에서 실제 값을 사용할 수 있게 하는 기능입니다.

const fs = require('fs')

// Promise를 반환하는 함수를 정의합니다.
function readFile_pr (fname) {
    return new Promise((resolve) => {
        fs.readFile(fname, 'utf-8',(err,s)=>{
            resolve(s)
        })
    })
}

//차례대로 텍스트 파일을 읽어 들입니다.
readFile_pr('a.txt')
.then((text) => {
    console.log('a.txt를 읽어 들였습니다.',text)
    return readFile_pr('b.txt')
})
.then((text) => {
    console.log('b.txt를 읽어 들였습니다.',text)
    return readFile_pr('c.txt')
})
.then((text) => {
    console.log('c.txt를 읽어 들였습니다.',text)
})

Promise를 사용하는 경우에는 일단 Promise 객체를 반환하는 함수를 준비합니다.

그리고 작성한것 처럼 순서대로 파일을 읽어 들일 수 있습니다. 비동기 처리가 완료되면 then() 메서드 내부에 작성한 함수가 실행됩니다.


Generator

제너레이터는 반복 처리가 가능한 이터레이터(Iterator)를 쉽게 구현 할 때 사용하는 기능입니다.

const fs = require('js')


//비동기 처리 완료를 기다리고, 다음 함수를 연속해서 호출하는 함수
function read_gfn (g,fname) {
    fs.readFile(fname, 'utf-8', (err, data) => {
        g.next(data)
    })
}

//제너레이터 함수를 정의합니다.
const g = (function * () {
    const a = yield read_gfn(g, 'a.txt')
    const b = yield read_gfn(g, 'b.txt')
    const c = yield read_gfn(g, 'c.txt')
})()