본문 바로가기

Programming/Javascript

Javascript 프로미스 promise 비동기 async await JS

728x90
const p1 = new Promise((resolve, reject) => {
  resolve('success');
});
p1.then((data) => console.log(data)); // success

const p2 = new Promise((resolve, reject) => {
  reject('error');
});
p2.catch((data) => console.log(data)); // error

p1.then((data) => {console.log(data); return 'success2'}) // success
.then((data) => {console.log(data); return 'success3'}); // success2
// Promise {<fulfilled>: 'success3'}

resolve는 프로미스 성공, reject는 프로미스 실패를 의미
각각 then, catch에 매개변수로 전달

then에서 return 하면 Promise로 반환

function work(sec, callback){
	return new Promise((resolve, reject) => {
		setTimeout(() => {
			resolve(new Date().toISOString());
		}, sec*1000);
	});
}

work(1).then(result => {
	console.log("첫 번째 작업", result);
	return work(1);
}).then(result => {
	console.log("두 번째 작업", result);
});

async function asyncFunc() {
	console.log("asyncFunc Start");
	const result1 = await work(3);
	console.log("세 번째 작업", result1);
	const result2 = await work(1);
	console.log("네 번째 작업", result2);
	return "asyncFunc End";
}

asyncFunc().then(result => {
	console.log(result);
});

return work(1);

then에서 Promise를 반환

const result1 = await work(3);

async function 안에 await Promise 형태로 실행을 순서대로 하도록 제어

첫 번째, 두 번째 작업은 체이닝(Chaining) 방식으로 비동기 실행

세 번째, 네 번째 작업은 순차적(Sequential) 실행 방식

728x90

'Programming > Javascript' 카테고리의 다른 글

google 광고 제거  (0) 2025.04.11
엔터와 공백문자를 +와 '로 이은 문자 변환기  (0) 2023.07.17
정규 표현식 메소드 및 예시  (0) 2022.10.19
정규 표현식  (0) 2022.06.09
JavaScript Array  (0) 2022.05.07