JS

[JS] Promise

ssh9308 2022. 7. 29. 11:59
반응형

Promise 란?

 

Promise 란 자바스크립트에서 비동기 처리에 사용되는 객체이다.

 

Promise 객체가 만들어진 기원은 기존에는 비동기 처리시에 순서를 보장하기 위해서

 

Callback 함수를 사용했는데 이 callback 함수가 다루기고 힘들고, 코드가 더러워지는 경향을 보여

 

더 깔끔하게 비동기 처리를 할 수 있게 만들어주는 Promise 객체가 나오게 되었다.

 

 

Promise 는 대표적으로 3가지의 상태가 존재한다.

1. Pending(대기)

2. Fulfilled(이행)

3. Rejected(실패)

 

 

1. Pending(대기)

 

먼저 new Promise() 메서드를 호출하면 내부적으로 대기 상태가 된다.

 

또한, new Promise() 메서드를 호출할 때 콜백함수를 선언할수 있고 파라미터는 resolve, reject 이다.

 

// 대기 상태
new Promise();


// 기본인자값
new Promise(function(resolve,reject){

});

 

 

2. Fulfilled(이행)

 

여기서 Promise의 resolve 인자를 실행하면 이행 상태가 된다.

 

그리고 이행 상태가 되면 then() 을 이용하여 결과 값을 받을 수 있다.

 

const add = (a,b) => {
    return new Promise((resolve,reject) => {
        setTimeout(() => {
            resolve(a+b);
        },1000)
    })
}

add(20,30)
    .then((sum) => console.log(sum))

 

3. Rejected(실패)

 

Promise의 reject 인자를 실행하면 실패상태를 도출해주며 실패결과값은 catch() 로 받을 수 있다.

 

const add = (a,b) => {
    return new Promise((resolve,reject) => {
        setTimeout(() => {
        	//매개변수가 숫자가 아니면 에러를 발생시킨다.
            if (typeof a !== 'number' || typeof b !== 'number') reject('error'); 
            resolve(a+b);
        },1000)
    })
}

add(20,'30')
    .then((sum) => console.log(sum))
    .catch((err) => console.log(err))

 

여러개의 프로미스를 이용하려면 아래와 같이 이용할 수 있다.

const add = (a,b) => {
    return new Promise((resolve,reject) => {
        setTimeout(() => {
            if (typeof a !== 'number' || typeof b !== 'number') reject('error'); 
            resolve(a+b);
        },1000)
    })
}

add(20,30)
    .then((sum) => {
        console.log(sum)
        return add(sum,sum + 1)
    })
    .then((sum) => {
        console.log(sum)
        return add(sum,sum + 1)
    })
    .then((sum) => {
        console.log(sum)
    })
    .catch((err) => console.log(err))

반응형