[JS] Javascript #12 Summary

2 minute read

Javascript #12 Summary


  • promise chaning --> 가독성 떨어짐

  • 기존의 존재하는 것을 감싸서 간편하게 쓸 수 있는 API: syntatic sugar
    (ex. class, async)


async & await

  • clear style of using promise


async

promise example

status: pending

function fetchUser() {
    return new Promise((resolve, reject) => {
        // do network request in 10 secs...
        return 'bruce';
    });
}

const user = fetchUser();
console.log(user);
// Promise {<pending>}__proto__: Promise [[PromiseStatus]]: "pending" [[PromiseValue]]: undefined
  • resolve, reject 를 호출하지 않았기 때문에 status 가 pending


status: fulfilled

function fetchUser() {
    return new Promise((resolve, reject) => {
        // do network request in 10 secs...
        resolve('bruce');
    });
}

const user = fetchUser();
console.log(user);
// // Promise {<fulfilled>: "bruce"}__proto__: Promise [[PromiseStatus]]: "fulfilled" [[PromiseValue]]: "bruce"



async example

async function fetchUser() {
    // do network request in 10 secs...
    return 'bruce';
}

const user = fetchUser();
user.then(console.log);  // bruce (비동기 처리로 인해 마지막으로 출력된다.)
console.log(user);
// Promise {<fulfilled>: "bruce"}__proto__: Promise [[PromiseStatus]]: "fulfilled" [[PromiseValue]]: "bruce"

async 가 붙은 function 은 promise 객체를 반환하는 것을 알 수 있다.



async with await

  • awaitasync 가 붙은 function 내부에서만 사용 가능
function delay(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

async function getApple() {
    await delay(2000);
    return '🍎';
}

async function getBanana() {
    await delay(1000);
    return '🍌';
}
  • getBanana() 를 promise 로 구현하면 다음과 같다.
function getBanana() {
    return delay(1000)
    .then(() => '🍌');
}


  • promise chaning
function pickFruits() {
    return getApple()
    .then(apple => {
        return getBanana()
        .then(banana => `${apple} + ${banana}`);
    });
}

pickFruits().then(console.log);

>>> 🍎 + 🍌


  • async with await
async function pickFruits() {
    const apple = await getApple();
    const banana = await getBanana();
    return `${apple} + ${banana}`;
}

pickFruits().then(console.log);

>>> 🍎 + 🍌

위 코드의 문제점은 getApple(), getBanana() 각각 1초씩 걸려 독립적인 코드임에도 병렬처리가 안된다.


  • promise 를 활용한 병렬처리
async function pickFruits() {
    // promise 를 통해 병렬처리
    const applePromise = getApple();
    const bananaPromise = getBanana();

    // 동기화
    const apple = await applePromise;
    const banana = await bananaPromise;
    return `${apple} + ${banana}`;
}

pickAllFruits().then(console.log);

>>> 🍎 + 🍌

위 코드는 clean 하지 못하다.


  • promise 의 API (Promise.all)를 활용한 병렬처리
function pickAllFruits() {
    return Promise.all([getApple(), getBanana()])
    .then(fruits => fruits.join(' + '));
}
pickAllFruits().then(console.log);

>>> 🍎 + 🍌


  • Promise.race: 먼저 완료된 promise 객체 한개만 반환
function pickOnlyOne() {
    return Promise.race([getApple(), getBanana()]);
}

pickOnlyOne().then(console.log);

>>> 🍌

Leave a comment