Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 | 31 |
Tags
- CSS
- Three
- CV
- ps
- SOLID
- figma
- html
- sqlite
- vscode
- API
- PRISMA
- react
- Express
- ML
- ts
- postgresql
- DB
- review
- opencv
- UI
- frontend
- C++
- Linux
- GAN
- mongo
- Git
- js
- nodejs
- PyTorch
- python
Archives
- Today
- Total
아카이브
[JS] Syntax | 08. .then() 본문
1. .then()
.then은 Promise를 반환하는 작업이 끝난 뒤 작업을 이어 할 수 있게 해주는 구문입니다.
사용할 때는 목표하는 함수 뒤에 .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
'Language > JavaScript' 카테고리의 다른 글
[JS] Library | 01. Superstruct (0) | 2024.08.25 |
---|---|
[JS] Syntax | 09. Promise.all() (0) | 2024.07.27 |
[JS] Syntax | 07. await & async (0) | 2024.07.25 |
[JS] Syntax | 06. Promise (0) | 2024.07.24 |
[JS] Syntax | 05. Callback (0) | 2024.07.22 |
Comments