함수 a()의 파라미터로 b()라는 함수를 줄 때 b()를 콜백 함수라고 한다.
콜백 함수는 보통 비동기 작업 시 함수의 실행 순서를 지정해주기 위해 사용한다.
그런데 비동기 작업이 여러 개일 때 이들의 순서를 모두 콜백 함수로 지정하려고 한다면 계속 중첩되어, 코드가 알아보기 힘들어질 것이다.
function test(message, callback) {
axios.get("http://127.0.0.1:8080").then((response) => {
callback(message);
});
}
test("1", function(result) {
console.log(result);
test("2", function(result) {
console.log(result);
test("3", function(result) {
console.log(result);
});
});
});
위 코드는 axios 요청이 성공했다면 message를 출력하는 함수를 호출하는 코드이다.
1, 2, 3을 순서대로 출력하기 위해 점점 함수가 중첩된다. 이것을 Promise 객체로 바꿔 본다.
방법 1
function test2(message) {
const promise = axios.get("http://127.0.0.1:8080");
return promise.then(() => {
return message;
});
}
test2("1").then((result) => {
console.log(result)
return test2("2");
}).then((result) => {
console.log(result)
return test2("3");
}).then((result) => {
console.log(result)
});
axios라는 비동기 메소드는 Promise 객체를 리턴한다. 이를 promise라는 변수에 저장하여, test2()가 Promise 객체를 리턴하도록 하였다.
then은 Promise 객체를 리턴하며, axios가 정상적으로 수행되었다면 promise.then()이 실행되어, message를 담은 Promise 객체를 리턴한다.
마찬가지로 test2()가 정상적으로 결과값을 리턴했다면 then 내부의 동작이 실행된다.
방법 2
async function test2(message) {
const promise = axios.get("http://127.0.0.1:8080");
await promise;
return message;
}
다음과 같이 test2()를 async function을 통해 비동기 함수로 만드는 방법도 있다. async function은 방법 1 코드처럼 수동으로 Promise 객체를 리턴해주지 않아도 무조건 Promise 객체를 리턴한다.
await을 이용해 axios 응답을 받을 때까지 기다린 후 message를 리턴한다.
또한 Promise 객체의 장점 중 하나는 오류 처리를 하기가 쉽다는 것이다.
new Promise((resolve, reject) => {
setTimeout(() => {
resolve("settimeout");
}, 1000);
}).then((result) => {
console.log(result);
}).catch((error) => {
console.log("오류 발생");
});
만약 Promise 안에서 동작하는 함수가 정상적으로 동작한 경우에는 resolve를, 예외가 발생했다면 reject를 발생시킨다.
catch 내부에 예외가 발생했을 때 실행할 동작을 입력함으로써 간단하게 예외 처리가 가능하다.
'IT > JavaScript & TypeScript' 카테고리의 다른 글
| [JavaScript] 클로저를 통해 코드 최적화(Optimizing)하기 (0) | 2024.04.29 |
|---|---|
| [JavaScript] 클로저(Closure) (0) | 2024.04.24 |
| [JavaScript] 함수 선언문 vs 함수 표현식 (feat. 호이스팅, 렉시컬 환경) (0) | 2024.04.23 |
| [JavaScript] ES6 문법을 알아보자 (ECMAScript 2015) (1) | 2024.04.22 |
| [JavaScript] 자바스크립트 객체 비교 방법 (0) | 2024.02.23 |