Language/JavaScript

[JS] Syntax | 08. .then()

Rayi 2024. 7. 27. 13:32

1. .then()

.thenPromise를 반환하는 작업이 끝난 뒤 작업을 이어 할 수 있게 해주는 구문입니다.

사용할 때는 목표하는 함수 뒤에 .then()을 붙이고, 이어서 할 작업을 인자로 넘겨줍니다.

const thenFunc = () => {
	fetch("https://something.com")
    	.then(console.log("fetch done"))	// fetch()가 끝난 뒤 이어할 작업을 작성합니다.
}

then에서 작성할 작업에서 이전 함수(여기서는 fetch입니다)의 결과값을 사용해야 한다면,

아래와 같이 함수의 매개변수로 넘겨줄 수 있습니다.

const thenFunc = () => {
	fetch("https://something.com")
    	.then((res) => res.json())	// fetch()의 결과를 res로 넘겨줍니다.
}

한 번에 여러 개의 then 구문을 사용할 수도 있습니다.

const thenFunc = () => {
	fetch("https://something.com")
    	.then((res) => res.json())
        .then((res) => console.log(res))
}

then을 이용해 작성한 비동기 함수 역시 실행되는 동안 함수 바깥의 다른 작업을 실행시킵니다.

const thenFunc = () => {
	fetch("https://something.com")
    	.then((res) => res.json())
        .then((res) => console.log(res))
    console.log("1")
}

console.log("2")

thenFunc()

console.log("3")

// 출력 순서 :
// 2
// 3
// 1

2. .catch() & .finally()

.then()을 사용하면 .catch().finally()를 사용해 예외처리를 할 수 있습니다.

두 가지 모두 try-catch-finally를 통한 예외처리와 같은 역할을 합니다.

const thenFunc = () => {
	fetch("https://something.com")
    	.then((res) => res.json())
        .then((res) => console.log(res))
        .catch((error) => console.log("Error occured"))
        .finally(() => console.log("job finished"))
}
728x90