■ Promise
Promise란?
Promise는 콜백함수 대신 사용할 수 있는 코드 디자인 패턴입니다.
콜백함수와는 다르게 순차적으로 코드를 실행할 때, 코드가 옆으로 길어지지 않습니다.
또한 코드 실행이 실패했을 때에 특정 코드를 실행할 수 있도록 코드를 짤 수 있다는 장점이 있습니다.
Promise는 코드의 성공/실패 판정에 따라 상태가 변합니다.
성공/실패 판정 전에는 <pending>, 성공 후에는 <resolved>, 실패 후에는 <rejected>로 나오며,
성공을 실패난 대기 상태로 되돌릴 순 없습니다.
Promise의 생김새
var 프로미스 = new Promise(function(성공, 실패){
성공();
});
프로미스.then(function(){
}).catch(function(){
});
new Promise() 문법으로 변수 오브젝트를 하나 생성합니다.
그리고 만든 변수에 then() 을 붙이면 성공했을 때의 함수를 실행시켜 주며, catch() 를 붙이면 실패했을 때의 함수를 실행합니다.
Promise 예시
function 기다리기(시간) {
return new Promise(function (성공, 실패) {
setTimeout(function () {
// 시간이 지난 후에 성공 또는 실패를 결정합니다.
var 무작위 = Math.random();
if (무작위 < 0.5) {
성공(무작위 + ' 성공했어요!');
} else {
실패(무작위 + ' 실패했어요!');
}
}, 1000);
});
}
// 성공, 실패의 파라미터를 가져올 수 있습니다.
기다리기()
.then(function (결과) {
console.log(결과);
})
.catch(function (에러) {
console.log(에러);
});
위의 코드에서는 setTimeout 함수로 2초가 지난 후에 Promise를 반환합니다.
시간이 지나면 무작위 숫자를 생성하여 성공 또는 실패를 결정하고 결과를 반환합니다.
then 으로 성공 결과를 처리하고, catch 로 실패 결과를 처리하는 것을 볼 수 있습니다.
또한 Promise의 성공/결과 함수의 파라미터를 then이나 catch에서 가져와 쓰는 것도 가능합니다.
function 프로미스1() {
return new Promise(function (resolve, reject) {
setTimeout(function () {
resolve('비동기 작업 1 완료');
}, 2000);
});
}
function 프로미스2() {
return new Promise(function (resolve, reject) {
setTimeout(function () {
resolve('비동기 작업 2 완료');
}, 1500);
});
}
프로미스1()
.then(function (결과1) {
console.log(결과1);
return 프로미스2();
})
.then(function (결과2) {
console.log(결과2);
})
위의 예제에서는 프로미스1, 프로미스2 함수를 정의하고, then을 사용하여 결과를 처리하고 있습니다.
프로미스1이 완료되면 then을 사용하여 결과를 처리하고 프로미스2를 호출합니다.
이어서 프로미스2가 완료되면 then을 사용하여 결과를 처리하는 과정을 볼 수 있습니다.
■ async와 await
async
async는 function 앞에 위치하여 promise를 반환합니다.
async function 더하기(){
return 1 + 1
}
더하기().then(function(결과){
console.log(`더하기 값은 ${결과}`)
});
위의 예제를 보면 더하기 함수에 Promise를 쓰지 않았지만 then으로 성공 결과를 반환하는 것을 볼 수 있습니다.
await
await 키워드는 async 키워드를 쓴 함수 안에서 사용가능하며, then() 문법 대신에 사용이 가능합니다.
async function 더하기(){
var 어려운연산 = new Promise((성공, 실패)=>{
var 결과 = 1 + 1;
성공(결과);
});
var 결과 = await 어려운연산;
console.log(결과);
}
더하기();
await 키워드를 사용하면 Promise를 기다린 다음에 완료되면 결과를 변수에 담아줍니다.
주의할 점으로는 비동기식 처리되는 코드를 담을 때는 await을 기다리는 동안 브라우저가 잠깐 멈출 수 있다는 점입니다.
try catch
async function 더하기(){
var 어려운연산 = new Promise((성공, 실패)=>{
실패(); // 실패로 바꿈
});
var 결과 = await 어려운연산;
console.log(결과);
}
더하기();
await은 실패하면 에러가 나고 코드가 멈춥니다.
Promise 에서 실행되는 코드를 실패로 바꿔보면 에러가 나오는 것을 확인할 수 있습니다.
async function 더하기(){
var 어려운연산 = new Promise((성공, 실패)=>{
실패();
});
try { var 결과 = await 어려운연산 }
catch { 어려운연산 Promise가 실패할 경우 실행할 코드 }
}
그렇기 때문에 실패할 경우, 코드실행을 멈추고 싶지 않다면 try, catch 문법을 사용할 수 있습니다.
try{} 안에 코드가 에러가 나서 멈출 경우에 catch {} 내부의 코드를 실행해주는 문법입니다.
'JavaScript' 카테고리의 다른 글
JavaScript(Symbol, Map, Set 자료형) (0) | 2023.06.28 |
---|---|
JavaScript(for in/for of 반복문) (0) | 2023.06.28 |
JavaScript(Event Loop) (0) | 2023.06.27 |
JavaScript(export, import) (0) | 2023.06.20 |
JavaScript(Destructuring) (0) | 2023.06.20 |