JavaScript : 외부 변수(Array 등) Promise로 처리하기

2021. 4. 14. 03:30Issue & Solution

먼저 JavaScript는 비동기로 처리되고, 이것에 대한 이해가 필요하다.

Java나 Python과는 다르게 JavaScript는 한 함수가 끝날때까지 기다려주지 않고, 바로 다음 요청을 실행하므로 프로그램 처리 속도가 빠르다.

다만 이렇기 때문에 주의해야 할 점들이 있다. 어떤 변수(혹은 함수)는 비동기 함수의 처리가 끝난 이후에 제대로 작동해야 하는 경우가 있다. 그렇지 않으면 undefined가 될 것이다.

이것을 Promise(ES8부터는 Promise 대신 async / await를 사용 할 수 있다.)를 이용해 비동기 함수를 동기식으로 처리할 수 있다.

외부 array에 내부 Promise함수의 item을 넣고 싶은데, Promise에 대한 이해가 조금 부족했어서 그런지 이상한 짓만 계속했다..

 

#Promise로 외부 Array에 값 넣기

비동기 함수 바깥의 변수 array에 함수가 처리된 이후의 변수를 push해서 처리가 완료된 array를 출력한다고 해보자.

안되는 예

...

const func = () => {
    const array = new Array();
    AsynchronousFunction(item => {
    	array.push(item);
    }
    console.log(array);
}

func();
//[]

이렇게 하면 당연히 안된다. 왜냐하면, AsynchnousFunction이 호출 되고 함수 내에서 result에 item을 넣기 전에 바로 console.log(result)를 호출하기 때문에, 빈 값이 나올 수밖에 없다.

아래와 같이 해도 안된다.

...

const func = async () => {
    const array = new Array();
    await AsynchronousFunction(item => {
    	array.push(item);
    }
    console.log(array);
}

func();
//[]

async / await를 사용해도 마찬가지이다. callback이 호출 되기 전 console.log(result)가 호출되기 때문이다.

 

방법

외부 변수 result에 값을 넣으려면 아래와 같이 Promise로 리턴을 해주고 resolve에 값을 넣어야 한다.

//방법1
...

const rightFunc = (array) => {
	return new Promise((resolve, reject) => {
    	AsynchronousFunction(item => {
        	array.push(item);
            if(item이 마지막 item이라면)	resolve(array);
    });
}

const func = () => {
    const array = new Array();
	rightFunc(array).then(result => {
    	console.log(result);
    }
}

func();
//[item1, item2, item3, ... ]

또는 아래와 같이 async / await를 사용하는 방법도 있다.

//방법1
...

const rightFunc = (array) => {
	return new Promise((resolve, reject) => {
    	AsynchronousFunction(item => {
        	array.push(item);
            if(item이 마지막 item이라면)	resolve(array);
    });
}

const func = async () => {
    const array = new Array();
    const result = await rightFunc(array);
    
    console.log(result);
}

func();
//[item1, item2, item3, ... ]

 

아무튼 이해 끝.

조만간 Promise 및 비동기에 대해 정리해서 글을 써봐야겠다.