JS 프로미스(Promise) 객체, async/await

서린·2024년 4월 25일
0

greenstudy

목록 보기
36/44
post-thumbnail

Promise 객체

  • JS의 비동기 프로그래밍에서 근간이 되는 기법
  • 콜백지옥을 개선하기위해서 등장한 기법

Promise 생성

const PRO = (str, ms) => {
	return new Promise((resolve, reject) => {
		setTimeout(()=>{
            if(str === 'A') {
                resolve('성공 : A임'); // 작업 성공 resolve() 호출
            } else {
                reject('실패 : A아님'); // 작업 실패 reject() 호출
            }
		}, ms);
	});
}

Promise 호출

PRO('B' , 5000)
.then(result => console.log('then : ' + result)) // resolve가 호출됐을 때
.catch(err => console.log('catch : ' + err)) // reject가 호출 됐을 때

콜백지옥과 개선

// 콜백지옥
setTimeout(() => {
	console.log('A');
	setTimeout( () => {
		console.log('B');
		setTimeout(() => {
			console.log('C')
		}, 1000);
	}, 2000);
}, 3000);

// 프로미스 객체로 개선
const PRO2 = (str, ms) => {
	return new Promise( (resolve) => {
		setTimeout(() => {
			console.log(str);
			resolve();
		}, ms);
	});
}

PRO2('A', 3000)
.then(() => PRO2('B', 2000))
.then(() => PRO2('C', 1000))
.catch(() => console.log('ERROR'))
.finally(() => console.log('파이널리'));

병렬 처리 방법(Promise.all())

const myLoop = cnt => {
    for(let i = 0; i < cnt; i++) {
          
    }
    console.log('myLoop 종료 : ' + cnt);
}

// myLoop(100000000);
// myLoop(10000000);
// myLoop(1000000);

Promise.all([myLoop(100000000), myLoop(10000000), myLoop(1000000)]); // 여러 개의 Promise 들을 비동기적으로 실행하여 처리

async/await란?

  • Promise 체이닝 또한 연결이 많아 질 경우 코드가 난잡해 질 수 있어 async & await를 도입
  • 코드 작성 부분을 유지보수와 가독성 좋게 해주나, 내부적으로는 Promise를 사용해 비동기 처리를 하므로 Promise를 대체하는 방법은 아니다.
  • function 키워드 앞에 async 키워드를 붙여주고, 비동키 처리되는 부분 앞에 await 키워드를 붙여주어 구현
const PRO2 = (str, ms) => {
	return new Promise( (resolve) => {
		setTimeout(() => {
			console.log(str);
			resolve();
		}, ms);
	});
}

PRO2('A', 3000)
.then(() => PRO2('B', 2000))
.then(() => PRO2('C', 1000))
.catch(() => console.log('ERROR'))
.finally(() => console.log('파이널리'));

const myAsync = async () => {
    try {
    await PRO2('A', 3000);
    await PRO2('B', 3000);
    await PRO2('C', 3000);
    } catch(err) {
        console.log(err);
    }
}
profile
개발 일기 ( •̀ ω •́ )✧

0개의 댓글

관련 채용 정보