Home Javascript Asynchronous
Post
Cancel

Javascript Asynchronous

javascript에서 비동기처리 방법을 알아봅시다.


javascript is synchronous

자바스크립트는 hositing된 이후부터 코드가 하나씩 처리됩니다.

hositing이란 var, function declartion등 자동적으로 위로 올라가는 것

그렇기 때문에 자바스크립트는 비동기처리를 위해 callback, promiss, async/await 방법이 존재합니다.

Callback

첫번째 방법으로 자바스크립트에서 콜백함수를 이용할 수 있습니다.
함수 실행 결과 값을 리턴이 아닌 매개변수로 넘어온 함수를 호출해서 넘겨주는 방식을 callback 이라 하며, 이때 매개변수로 넘어온 함수를 callback function라고 합니다.

Callback expamle Code

아래의 코드를 실행하면 console에 1,2 async callback 순으로 보여지게 됩니다.
이런식으로 콜백함수를 이용하여 비동기 처리를 할 수 있습니다.
하지만 콜백지옥의 문제점이 발생할 수 있습니다.

1
2
3
4
5
6
function printWithDelay(print, timeout){
    setTimeout(print,timeout);
}
console.log(1);
printWithDelay(()=> console.log('async callback'), 2000);
console.log(2);

Promise

promise는 비동기처리를 할때 사용되는 콜백함수 대신에 사용할 수 있는 오브젝트 입니다.
특징으로 state, produser/consumer가 있습니다.

state는 현재 수행 중인지(pending), 수행 결과가 성공했는지(fulfilled) 실패했는지(rejected) 현재 상태를 말합니다.
정보를 제공하는 produser, 정보를 사용하는 consumer로 이해할 수 있습니다.

특징으로 프로미스를 생성할 때 executor 함수가 자동으로 실행됩니다.

Promise example Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//1.Producer
const promise = new Promise((resolve,reject) => {
    //doing some work
    setTimeout(() => {
        resolve('success'); // 성공 시 
        reject(new Error("error")); // 에러 시
    },2000);
});

//2. Consumer: then, catch, finally
promise
.then((value) => {
    console.log(value); // -> console.log("success");
})
.catch(error => {
    console.log(error);
})
.finally(() => { //마지막에 무조건 호출됨
    console.log("filnally"); 
});

Async/Await

promise 또한 계속 chaining 하면 코드가 복잡하게 되어 async/await을 사용할 수 있습니다.
async function를 실행하면 promise 객체가 반환되며 async function의 return 값promise의 resolve값이 됩니다.

await 키워드는 async function안에서만 사용할 수 있습니다. await는 promise 상태가 다 진행될 때까지 기다렸다가 다음으로 진행하게 됩니다. await 위치는 promise 객체를 생성하는 함수 앞에 놓입니다.

Aysnc/Await example Code

async/await으로 동기적 코드처럼 작성이 가능합니다.
async/await의 오류는 try/catch로 잡아 낼 수 있습니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
//1. Async
async function fetchUser(){
    return "success";
}
//2. await
function delay(ms){
    return new Promise(resolve => setTimeout(resolve, ms));
}

async function getApple() {
    await delay(3000);
    return 'apple'
}

async function getBanana() {
    await delay(3000);
    return 'banana'
}

// 아래의 코드는 병렬 처리의 문제가 있음 Apple을 3초를 기다리고, Banana의 3초를 기다려서 6초가 걸림 
async function pickFruits(){
    try{
    const apple = await getApple();
    const banana = await getBanana();
    return `${apple} + ${banana}`;
    } catch(){

    }
}

pickFruits().then(console.log);

//3. usefult promise APis
// Promise.all, Promise.race
function pickAllFruits(){
    return Promise.all([getApple(), getBanana()]).then(fruits => 
     fruits.join(' + ');
    )
}

Reference

  • https://www.youtube.com/watch?v=wcsVjmHrUQg&list=PLv2d7VI9OotTVOL4QmPfvJWPJvkmv6h-2