본문 바로가기

T.I.L

23-05-25 T.I.L 비동기 작업의 동기적 표현 Promise + Async/await 로직 해석(콜백함수)

문제 설명

비동기 작업이란 순서가 보장되어 있지 않은 함수를 의미한다. 실행 중인 함수의 완료 여부와는 관계 없이 다음 코드로 넘어가는 방식이다. 동기는 실행 중인 함수가 완료가 되어야 다음 코드로 넘어간다. Proimse는 비동기 함수를 동기적인 방식으로 만드는 함수다. Promise의 콜백함수 내부에 resolve(함수를 호출하는 구문)가 있을 경우 resolve가 실행되기 전까지 다음으로 넘어가지 않는다.

Async/await 는 비동기 작업을 동기적으로 표현할 수 있는 수단 중 하나이다.

하지만 Async/await의 로직이 어떤 식으로 작용이 되는지 이해가 잘 가지 않는다.

시도

var addCoffee = function (name) {
	return new Promise(function (resolve) {
		setTimeout(function(){
			resolve(name);
		}, 500);
	});
};
var coffeeMaker = async function () {
	var coffeeList = '';
	var _addCoffee = async function (name) {
		coffeeList += (coffeeList ? ', ' : '') + await addCoffee(name);
	};
	await _addCoffee('에스프레소');
	console.log(coffeeList);
	await _addCoffee('아메리카노');
	console.log(coffeeList);
	await _addCoffee('카페모카');
	console.log(coffeeList);
	await _addCoffee('카페라떼');
	console.log(coffeeList);
};
coffeeMaker();

 다음은 Async/await의 예제 코드이다. 코드 리딩을 통해서 로직을 이해해보려고 한다!

이 코드는 '에스프레소', '아메리카노', '카페모카', '카페라떼' 가 차례대로 console.log에 찍게 하기 위한 코드다.

먼저 addCoffee라는 식별자에 함수를 할당했다.

var addCoffee = function (name) {
	return new Promise(function (resolve) {
		setTimeout(function(){
			resolve(name);
		}, 500);
	});
};

 

addCoffee는 name이 매게 변수인 new Promise 함수다.

new Promise는 콜백함수가 매개변수이다.

콜백함수 function (resolve) 는 {setTimeout(function(){resolve(name);}, 500})를 또 콜백함수로 지니고있다.

 setTimeout(function(){resolve(name);}, 500)은..resolve(name)을 0.5초뒤에 실행한다는 의미이다.

resolve(name)이 실행이 된다는게 어떤 뜻인지 잘 모르겠다. 

그래서 resolve 안에 name을 지우고 resolve()인채로 코드를 작동했다.

결과는 

undefined

undefined,undefined

undefined,undefined,undefined

undefined,undefined,undefined,undefined

resolve(name)은 매개변수라는 것을 이해했다.

var coffeeMaker = async function () {
	var coffeeList = '';
	var _addCoffee = async function (name) {
		coffeeList += (coffeeList ? ', ' : '') + await addCoffee(name);
	};

 그 다음은 coffeeMaker의 함수 선언문이 나온다.

async function () 는 var coffeeList = ' '; 빈 문자열과 var _addCoffee = async function (name) 함수를 선언했다.

coffeeList += (coffeeList ? ', ' : ' ') + await addCoffee(name); 이건

coffeeList = coffeeList+ (coffeeList ?   ' , '  :  ' ') + await addCoffee(name); 이거와 같다고 볼 수 있다. 

잘 모르겠으니 천천히 대입해보자.

현재 coffeeList는 =' ' 이다. 그리고 (' '===true)는false다. 즉  (coffeeList ?   ' , '  :  ' ')=' '라 볼 수 있다.

coffeeList=' '+' '+ await addCoffee(name) 다. 

해결

        await _addCoffee('에스프레소');
	console.log(coffeeList);
	await _addCoffee('아메리카노');
	console.log(coffeeList);
	await _addCoffee('카페모카');
	console.log(coffeeList);
	await _addCoffee('카페라떼');
	console.log(coffeeList);

 

 지금까진 coffeeMaker()의 변수, 함수 선언문이었고 지금이 coffeeMaker의함수가 실행되는 부분이다.

 

 await_addCoffee('에스프레소') 이건 _addCoffee('에스프레소') 이 함수의 실행이 끝나야 다음 코드로 넘어간다는 뜻이다.

 

_addCoffee('에스프레소')=async function ('에스프레소') {coffeeList += (coffeeList ? ', ' : '') + await addCoffee(name);};

 

현재 coffeeList는 =' '다.

 

그리고  addCoffee('에스프레소')=function ('에스프레소') {
return new Promise(function (resolve) {
setTimeout(function(){
resolve('에스프레소');
}, 500);
});
};

즉  addCoffee('에스프레소')= 0.5초의 시간 뒤에 '에스프레소'란 결과를 낸다.

 

coffeeList=' '+' '+'에스프레소'

 

console.log(coffeeList)=0.5초 뒤의 '에스프레소' 가 된다는 뜻이다.

awaitasync가 있을 때 그 다음 코드로 넘어가게 한다.

 

_addCoffee('아메리카노')=async function ('아메리카노') {coffeeList += (coffeeList ? ', ' : ' ') + await addCoffee(name);};

coffeeList='에스프레소' 이기 때문에 coffeeList ? ', ' : ' ' 의 결과는 ',' 쉼표가 된다.

coffeeList='에스프레소' + ' , ' +await addCoffee('아메리카노')

                    ='에스프레소' + ' , ' + 0.5초 뒤의 '아메리카노' 

                    ='에스프레소' , 0.5초 뒤의 '아메리카노' 란 뜻이 된다.

 

알게된 점

비동기 작업의 동기화 방법 중 Promise와 Async/await의 로직에 대해서 이해할 수 있었다.

콜백함수의 구조에 대한 이해도가 약간 상승했다.