const sampleFunction =() => {
testFunc()
.then(result => console.log(result))
}
SampleFunction이라는 함수 내부에 로직이 도는데 testFunc()가 돌고 나서 Promise 객체 (쉽게 말해 함수가 다 돌고 난 후 반환되는 return 값)를 반환한다.
이때 .then()을 걸어주는데, 반환되는 값을 result라는 이름으로 받고, 그 값을 console.log를 통해 출력하는 로직이다.
즉 textFunc() 가 정상적으로 돌고 ‘나면’ 결과 값을 result라는 이름으로 받아아서 순차적으로 다른 작업을 진행할 수 있는데 그 작업이 여기서는 Console에 해당 내용을 출력하는 것이다. (반환되는 값이 없을 경우엔 result = undefined 로 반환한다.)
일반적으로 예외 처리는 다음과 같이 한다.
// 방법1 : then 이후 catch를 통해 예외를 받는다.
const sampleFunc01 = () => {
asyncFunc()
.then(result => console.log(result))
.catch(err => console.log(err))
}
// 방법2 : then() 내부 인자를 통해서 직접 받는다.
// Promise.then()의 안에 들어가는 인자 자체가 기본적으로 ('성공시 반환값', '실패시 반환값')
// 형태로 2가지이며 일반적으로 쓸때 앞의 하나만 쓰면서 성공 시 값만 가져오는 것 뿐이다.
const sampleFunc02 = () => {
asyncFunc()
.then(
result => console.log(result),
err => console.log(err)
)
}
문제는 연속적으로 로직 완료 → 다음 로직 → 다음 로직 완료 → 다다음 로직… 식으로 흘러가게 되면 가독성이 떨어지게 된다.
const mainFunction = () => {
firstFunc()
.then(secondFunc()
.then(thirdFunc()
.then(forthFunc()
...
)
)
)
}
//then 활용 시
const sampleFunction =() => {
testFunc()
.then(result => console.log(result))
}
//await, async 활용시
const sampleFunction = async() => {
const result = await testFunc()
console.log(result)
}
await를 사용하려면 async 키워드가 선언된 함수 내부에 있어야 한다. 위에서는 sampleFunction이 async로 감싸진 익명함수이며, 그 안에 await testFunc()가 들어있다.
우측 코드에서 result는 await를 붙인 testFunc()가 다 완료 되어야만 변수로 선언이 되고 그 이후 console.log를 통해 출력하는 과정을 거친다.
async, await의 예외처리는 다음과 같이 한다.
const sampleFunc01 = async() => {
try {
const result = await asyncFunc();
console.log(result)
} catch (err) {
console.log(err)
}
}