[ javascript ] promise > javascript&jQuery

본문 바로가기

사이트 내 전체검색

javascript&jQuery

[ javascript ] promise

작성일 21-02-21 01:42

페이지 정보

작성자 웹지기 조회 3,334회 댓글 0건

본문

'use strict'


//promse 코드를 이용해서 비동기식으로 처리 하는 방법

//Promse is a JavaScript object for asynchronous operation.

//state : pending(진행중) -> fulfilled(성공적으로 종료) or rejected(파일을 찾을 수 없거나 문제가 생기면)

//Producer(원하는 기능을 수행해서 해당데이터를 만듬) vs Consumer(해당 데이터를 소비)


//1. Producer

//promise가 만들어지는 순간 네트워크 통신을 수행하게 된다.

//버튼을 눌러서 네트워크를 연결해야 할 경우는 사용하지 않는게 좋다.

//when new Promise is created, the executor runs automatically.

//promise 변수를 Promise Object 로 만들자

const promise = new Promise((resolve, reject) => {

   //doing some heavy work(network, read files) 비동기처리가 유리

   console.log('doing something...');

   setTimeout(()=>{

        //resolve('test'); //성공했을 때 나타내는 핸들링

        reject(new Error('no network')) //오류를 나타내는 핸들링

   }, 2000);

});


//2. Consumers : then, catch, finally

//아래 .then은 promise가 리턴이되고 자신을 호출하는것과 같아서

//그래서 다시 promise에 .catch를 등록할 수가 있게 된다.

//※※※※※※※※※이것을 체이닝이라고 한다.  굉장히 중요함.

promise

    .then((value)=>{ //성공적인 부분

        console.log(value);

    })

    .catch(error=>{ //오류가 발생하는 부분을 console.log로 출력

        console.log(error);

    })

    .finally(()=>{ //성공과 실패에 상관없이 무조건 실행하고 싶을 때

        console.log('finally');

    });


//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));


//4. Error Handling

const getHen = () => 

    new Promise((resolve, reject) => {

        setTimeout(() => resolve('Chicken'), 1000);

    });


const getEgg = hen => 

    new Promise((resolve, reject) => {

        //오류처리구문

        setTimeout(() => reject(new Error(`${hen} => Egg `)), 1000);

        //정상구문

        //setTimeout(() => resolve(`${hen} => Egg `), 1000);

    });


const cook = egg => 

    new Promise((resolve, reject) => {

        setTimeout(() => resolve(`${egg}=> Fry`), 1000);

    });


getHen()

    .then(hen => getEgg(hen))

    .then(egg => cook(egg))

    .then(meal => console.log(meal));


//콜백함수를 전달할 때 받아오는 value를 하나로 호출한 경우는 생략이 가능하다.

//.then(han=> getEgg(hen))   ==> .then(getEgg)

//.then(egg =>cook(egg)) ==> .then(cook)

//.then(meal => console.log(meal)) ==> .then(console.log)

//즉 getHen().then(getEgg).then(cook).then(console.log); 

//이렇게 사용이 가능하다

//프리티어 포멧에서 한줄로 작성

getHen()

    .then(getEgg)

    //오류처리구문이 존재할 때 대체구문으로 진행을 마무하게 해주는 catch문

    .catch(error => {

        return 'bread';

    })

    .then(cook)

    .then(console.log)

    .catch(console.log); //오류처리


추천0

비추천 0

댓글목록

등록된 댓글이 없습니다.

전체 63건 1 페이지

이미지 목록

게시물 검색
Copyright © 즐거운 코딩 생활 ( funyphp ). All rights reserved.
PC 버전으로 보기