반응형
Promise 공식 문서
Promise - JavaScript | MDN
Promise 객체는 비동기 작업이 맞이할 미래의 완료 또는 실패와 그 결과 값을 나타냅니다.
developer.mozilla.org
resolve 메서드를 이용한 비동기 처리 방법
function a() {
return new Promise ((resolve) => {
setTimeout(() => {
console.log('A')
resolve()
}, 1000)
})
}
function b() {
return new Promise ((resolve) => {
setTimeout(() => {
console.log('B')
resolve()
}, 1000)
})
}
function c() {
return new Promise ((resolve) => {
setTimeout(() => {
console.log('C')
resolve()
}, 1000)
})
}
function d() {
return new Promise ((resolve) => {
setTimeout(() => {
console.log('D')
resolve()
}, 1000)
})
}
function test() {
// const promise = a()
// promise.then(() => {
// console.log('B')
// })
// a().then(() => {
// b().then(() => {
// c().then(() => {
// d().then(() => {
// console.log('Done!')
// })
// })
// })
// })
// a().then(() => {
// return b()
// }).then(() => {
// return c()
// }).then(() => {
// return d()
// }).then(() => {
// console.log('Done!!!')
// })
a()
.then(() => b())
.then(() => c())
.then(() => d())
.then(() => {
console.log('Done!!!!')
})
}
test()
브라우저 확인
reject를 이용하여 예외처리를 진행하는 방법
function a(number) {
return new Promise ((resolve, reject) => {
if (number > 4) {
// then 메소드가 실행되지 않도록 설정
reject();
// 변수가 4이상일 경우 아래 코드가 실행되지 않도록 설정
return
}
setTimeout(() => {
console.log('A')
resolve()
}, 1000)
})
}
// function test() {
// a(7)
// .then(() => {
// console.log('Resolve!')
// })
// .catch(() => {
// console.log('Reject!')
// })
// .finally(() => {
// console.log('Done!')
// })
// }
// async, await를 이용하여 예외처리를 하는 방법
async function test() {
try {
await a(8)
console.log('Resolve!')
} catch (error) {
console.log('Reject')
} finally {
console.log('Done!')
}
}
test()
브라우저 확인
반응형
'프론트엔드 > Vue.js' 카테고리의 다른 글
container 너비 사용자 지정 (0) | 2021.09.23 |
---|---|
비동기 - API 비동기 처리 연습 (0) | 2021.09.13 |
비동기 - 콜백(callback)과 프로미스 객체 (0) | 2021.09.09 |
영화목록에서 ID 중복 제거 (0) | 2021.09.09 |
Search - 버튼 구현하기 (0) | 2021.08.31 |