기록하는 개발자

<React 파헤치기-08> ES6주요문법 - 6. 비동기 함수 본문

카테고리 없음

<React 파헤치기-08> ES6주요문법 - 6. 비동기 함수

밍맹030 2021. 12. 11. 16:37
728x90

Promise(프로미스)

비동기 상태를 값으로 다룰 수 있는 객체다.

 

Promise의 세 가지 상태

1. 대기 중(pending): 결과를 기다리는 중이다.

2. 이행됨(fulfilled): 수행이 정상적으로 끝났고 결괏값을 가지고 있다.

3. 거부됨(rejected): 수행이 비정상적으로 끝났다.

- 이행됨, 거부 상태를 처리됨(settled)상태라고 부른다. 프로미스는 처리됨 상태가 되면 더 이상 다른 상태로 변경되지 않는다.
   →대기 중 상태일 때만 이행됨 또는 거부됨 상태로 변할 수 있다.

 

then

처리됨(settled)상태가 된 프로미스를 처리할 때 사용되는 메소드다. Promise가 처리됨 상태가 되면 then 메서드의 인수로 전달된 함수가 호출된다.

 

비동기 함수 예제

// 이해를 돕기 위한 Promise 예제(실제 Promise class 아님)
class Promise{
	constructor(fn){
		const resolve = (...args) =>{
			if(typeof this.onDone==='function') this.onDone(...args);
			if(typeof this.onComplete==='function') this.onComplete(...args);
		}
		const reject = (...args) =>{
			if(typeof this.onError==='function') this.onError(...args);
			if(typeof this.onComplete==='function') this.onComplete(...args);
		}
        fn(resolve, reject);
    }
    then(onDone, onError){
        this.onDone=onDone;
        this.onError=onError;
        return this;
    }
    catch(onError){
        this.onError=onError;
        return this;
    }
    finally(onComplete){
        this.onComplete=onComplete;
        return this;
    }
}
// <1>
const work1 = () => 
	new Promise((resolve) => {
    	setTimeout(() => resolve("작업1 완료", 100);
    });

// <2>
const work2 = () => 
	new Promise((resolve) => {
    	setTimeout(() => resolve("작업2 완료", 200);
    });
 
// <3>
const work3 = () => 
	new Promise((resolve) => {
    	setTimeout(() => resolve("작업3 완료", 300);
    });

// <4>
function urgentWork(){
	console.log("긴급 작업");
}

// <5>
const firstWorkDone = (msg1) => {
    console.log('done after 100ms:'+msg1);
    return work2();
}

// <6>
work1()
    .then(firstWorkDone)
    .then((msg2) => {
		console.log('done after 100ms:'+msg1);
    	return work3();
	})
    .then((msg3) => {
		console.log('done after 100ms:'+msg1);
	});
    
urgentWork();

 

※ new를 통해 Promise 객체 생성하면 '대기중'상태 → Promise 객체 내 resolve or reject 함수 호출

    → Promise 객체 '처리됨' 상태 → then으로 전달된 메소드 호출

 

1. work1, work2, work3 함수 모두 <1>,<2>,<3>에서 확인할 수 있듯이 promise객체를 return 한다.

2. <6>에서 work1() 함수가 실행되기 전 비동기 함수가 아닌 urgentWork 함수가 먼저 실행된다.

     →  console 출력 :  "긴급 작업"

3. <6>에서 work1 함수가 100ms 후에 promise 객체를 return 한다. 이 때 promise객체는 new로 생성되어 '대기중' 상태가 된다.

4. promise객체의 resolve 함수가 호출되므로써 Promise 객체는 '대기중'상태에서 '처리됨' 상태가 된다.

// promise 객체는 setTimeout함수를 통해 resolve 함수를 호출한다.
const work1 = () => 
	new Promise((resolve) => {
    	setTimeout(() => resolve("작업1 완료", 100);
    });

// promise class의 resolve 함수
    const resolve = (...args) =>{
        if(typeof this.onDone==='function') this.onDone(...args);
        if(typeof this.onComplete==='function') this.onComplete(...args);
    }

5. 처리됨 상태가 되었으므로 then을 통해 전달된 firstWorkDone 함수가 호출 된다.

    firstWorkDone 함수는 Promise class의 then에 정의된 onDone으로 전달된다.

    resolve 함수 내에서 onDone으로 전달된 firstWorkDone이 function인지 확인되면 firstWorkDone 함수에 resolve를 통해 넘어온 문자열("작업1 완료")을 전달한다.

const firstWorkDone = (msg1) => {
    console.log('done after 100ms:'+msg1);
    return work2();
}

// promise class에서의 then 정의
    then(onDone, onError){
        this.onDone=onDone;
        this.onError=onError;
        return this;
    }
    
// promise class의 resolve 함수
    const resolve = (...args) =>{ //...args : "작업1 완료"
        if(typeof this.onDone==='function') this.onDone(...args);
        if(typeof this.onComplete==='function') this.onComplete(...args);
    }

 

5. firstWorkDone 함수는 콘솔창에 완료 문구 출력 후 work2함수를 호출한다.

     →  console 출력 :  done after 100ms: 작업1 완료

6. work2함수가 200ms 뒤에 promise 객체를 return하고 work1과 동일한 방식으로 console에 문구가 출력된다.

7. work3 동일

 

이 글만으로 이해하기 어려우니 비동기 함수에 대해 더욱 자세히 설명해주신 분의 글을 참고하자 : https://velog.io/@cyheum/React-%EC%A0%95%EB%B3%B5%EA%B8%B0-ES6-%ED%96%A5%EC%83%81%EB%90%9C-%EB%B9%84%EB%8F%99%EA%B8%B0-%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%98%EB%B0%8D-%EC%8B%A4%EC%A0%84-%EB%A6%AC%EC%95%A1%ED%8A%B8-%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%98%EB%B0%8D-3

 

[React 정복기] ES6+ 향상된 비동기 프로그래밍 (실전 리액트 프로그래밍) - 3

실전 리액트 프로그래밍 개정판 - 이재승 지음 (참고자료)

velog.io

 

728x90