능글맞은 구렁이

JavaScript - Promise 본문

JS/JavaScript

JavaScript - Promise

보라색츄르 2023. 7. 12. 15:31

먼저, 동기(Synchronous) VS 비동기(asynchronous) 란?

 

쉽게, 동기는 직렬 비동기는 병렬이다.

javaScript는 태스크를 순차적으로 진행시키는 동기적 언어이다.

 


하지만, 보통 서버와 통신할 때 가장 많은 시간이 소요되므로 네트워크 관련 작업들은 비동기적으로 구현되어 있다고 한다.
따라서 자바스크립트 외적인 것, 대표적으로 AJAX가 있다.

비동기로 처리하는 방식은 효율성을 상승시켜 처리 속도를 높여준다.

Promise란?

Promise는 자바스크립트에서 비동기 처리를 간편하게 처리할 수 있도록 도와주는 객체이다.

여기서 자바스크립트의 비동기 처리란

‘특정 코드의 실행이 완료될 때까지 기다리지 않고 다음 코드를 먼저 수행하는 자바스크립트의 특성’

을 의미합니다.

Pending : 대기 (비동기 로직 처리의 미완료 상태)
Fulfilled : 이행 (비동기 로직 처리가 완료된 상태로 Promise 결괏값 반환 상태
Rejected : 실패 (비동기 로직 처리의 실패 또는 오류 상태)

 

 

간단한 예시

step1

fetch('https://jsonplaceholder.typicode.com/posts')
    .then(function(response){
        console.log('response',response);
    })
    .catch(function(reason){
        console.log('reason', reason);
    });

1) 성공시 then

-> respose의 값이 primise라면 비동기이다.

-> 리턴한 값은 2개의 함수를 또는 메소드를 사용해서 활용할 수 있다.

2) 실패시 catch

 

 

step2

fetch('https://jsonplaceholder.typicode.com/posts')
    .then(function(response){
       return response.json();
    })
    .catch(function(reason){
        console.log('reason', reason);
    }) 
    .then(function(data){
        console.log('data', data);
    });

 

 

new Promise 만들기

function job1(){
    return new Promise(function(resolve, reject){
        setTimeout(function(){
            resolve('fail!');
        }, 2000);
    });
}

function job2(){
    return new Promise(function(resolve, reject){
        setTimeout(function(){
            resolve('success');
        }, 2000);
    });
}

job1()
    .then(function(data){
        console.log('data', data);
        return job2();
    })
    .catch(function(reason){
        console.log('reason', reason)
        return Promise.reject(reason);
    })
    .then(function(data){
        console.log('data2', data);

    })

'JS > JavaScript' 카테고리의 다른 글

JavaScript - Async & Await  (0) 2023.07.13
JavaScript - CallBack함수  (1) 2023.07.09
JavaScript - 키보드 키코드 값  (0) 2022.05.11
javaScript -모달  (0) 2022.01.17
javaScript_div안에 div추가  (0) 2021.07.20
Comments