본문 바로가기

programming/db, web, node.js

[JavaScript] Promise

 

Promise 동작은 오랜 만에 보면 자꾸 혼동이 되어서, 아래 정리해 두었다.

 

(아래 코드는 "리액트를 다루는 기술 - 김민준 저" 15장에서 발췌하여, 일부 수정한 것이다.)

 

function printLater(number) {
	console.log('new promise()');
	return new Promise(
		(resolve, reject) => {
			if(number > 4) {
				return reject('number is greater than 4');
			}
			setTimeout(
				() => {
					console.log(number);
					resolve(number + 1);
				}, 1000
			)
		}
	)
}

printLater(1)
.then(num => printLater(num))
.then(num => printLater(num))
.then(num => printLater(num))
.then(num => printLater(num))
.catch(e => console.log(e));

console.log('3개의 모든 .then 예약과 catch 예약이 즉각 실행되었음.');

 

 

printLater(1)  (0초 시점)
4개의 모든 .then 예약과 catch 예약이 즉각 실행되었음.  (0초 시점)
1   (1초 시점)
printLater(2)   (1초 시점)
2   (2초 시점)
printLater(3)   (2초 시점)
3   (3초 시점)
printLater(4)   (3초 시점)
4   (4초 시점)
printLater(5)   (4초 시점)
number is greater than 4   (4초 시점)

 

 

0초 시점) 1번째 Promise가 생성, 리턴되어, 이 Promise에 대해 총 4개의 then과 1개의 catch가 실행되면서 4개의 resolve 콜백, 1개의 catch 콜백이 전달된다.

1초 시점) 1번 resolve 콜백 실행 => 2번째 Promise가 생성, 리턴 되어, 남은 3개의 콜백, 1개의 catch 콜백이 전달된다.

2초 시점) 2번 resolve 콜백 실행 => 3번째 Promise가 생성, 리턴 되어, 남은 2개의 콜백, 1개의 catch 콜백이 전달된다.

3초 시점) 3번 resolve 콜백 실행 => 4번째 Promise가 생성, 리턴 되어, 남은 1개의 콜백, 1개의 catch 콜백이 전달된다.

4초 시점) 4번 resolve 콜백 실행 => 5번째 Promise가 생성, 리턴 되어, catch 콜백 호출되고 끝남.

 

.then()이라는 동작은 일종의 예약이고, 이것은 즉각 예약 실행되는 것인데, 4개의 then이 모두 즉각 예약 실행된다.즉 .then( )에 전달된 콜백함수는 1초 간격으로 수행되지만 이 콜백함수를 받아들이는 4개의 then( ) 멤버함수는 모두 즉각 수행(예약) 완료된다.