nika-blog

프로미스(Promise) 본문

FE/JS

프로미스(Promise)

nika0 2021. 9. 1. 10:01

안녕하세요. 

오늘은 프로미스(Promise)에 관한 포스팅 입니다. 

 

 

콜백지옥을 탈출하기 위해 가장 좋은 방법이죠!

먼저 개념을 알아보면 아래와 같습니다. 

 

promise

Promise 객체는 비동기 작업이의 완료 또는 실패와 그 결과 값을 나타냅니다.

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Promise

 

Promise - JavaScript | MDN

Promise 객체는 비동기 작업이 맞이할 미래의 완료 또는 실패와 그 결과 값을 나타냅니다.

developer.mozilla.org

 

코드를 한번 살펴보며 다음과 같습니다. 

 

promise.js
'use strict';

//promise is a JavaScript object for asynchronous operation.
//State: pending -> fulfilled or rejected
//producer vs Consumer

//1. Producer
//Notice : when new Promise is created, the executor runs automatically.

const promise = new Promise((resolve, reject) => {
//    doing some heavy work (network, read files)
    console.log('doing something...');
    setTimeout(() => {
        // resolve('erice'); //.then 실행
        reject(new Error('no network'));//.catch 실행
    }, 2000);
});

// 2. Consumers: then, catch, finally
promise
    .then(value => {
        console.log(value);
    })
    .catch(error => {
        console.log(error);
    })
    .finally(()=>{
        console.log('finally');
    })

실행화면

 

주의할 점 : 새로운 Promise가 생성되면 executor가 자동으로 실행됩니다.

 

위 코드를 보시면, 완료가 되었을 때는 .then이 실행되고, 

실패시에는 .catch가 실행, 

모든 상황.finally 가 실행됨을 확인할 수 있습니다. 

 

promise chaining

 

promise.js

코드로 살펴보면 다음과 같습니다. 

//3. promise chaining
const fetchNumber = new Promise((resolve, reject) => {
    setTimeout(() => resolve(1), 1000);
});

fetchNumber
    .then(num => num * 2)
    .then(num => num * 3)
    .then(num => {
        return new Promise((resolve, reject) => {
            setTimeout(() => resolve(num - 1), 1000);
        });
    })
    .then(num => console.log(num));

//실행 결과
//5

 

프로미스를 사용하면, 콜백지옥 없이 깔끔하게 코드를 작성할 수 있습니다. 

오늘 포스팅은 여기까지에요!

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

Canvas  (0) 2022.02.24
JS - DOM 조작  (0) 2022.02.20
JS의 동기와 비동기  (0) 2021.08.30
JSON(Javascript Object Notation)  (0) 2021.08.29
콘솔(console) 잘 사용하는 법  (0) 2021.08.23