중요한 부분이라 일반적으로 추구하는 간략한 포스팅 보다 조금 설명이 길어질것 같다.
아래 코드는 버튼을 클릭했을 때 2초 뒤에 데이터를 받아오는 프로미스 객체를 promise
변수에 담는 로직이다.
<script>
let promise
function fetchName() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Jude')
}, 2000);
})
}
</script>
<button on:click={() => {
promise = fetchName()
}}>
Fetch name!
</button>
(스벨트 문법은 하이라이트가 제대로 안된다..)
프로미스 객체를 담은 promise
변수를 await
키워드 옆에 작성하고, then
옆의 매개 변수로는 반환되는 데이터를 기다렸다가 받을 수 있다.
<button on:click={() => {
promise = fetchName()
}}>
Fetch name!
</button>
{#await promise}
{:then res}
<h1>{res}</h1>
{/await}
버튼을 누르기 전 undefined
로 초기값이 출력된다.
<h1>undefined</h1>
res
데이터가 들어오기 전에 초기값
을 promise
변수에 넣어 지정할 수 있다.
지금은 promise
변수에 값이 없어서 undefined
가 출력된다.
promise
변수에 문자열로 초기값
을 설정해줄 수 있다.
초기값은 res
데이터가 출력되는 자리에 대신 출력된다.
let promise = '초기값...'
function fetchName() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Jude')
}, 2000);
})
}
<h1>초기값...</h1>
초기값이 설정됐다.
초기값을 res 대신 넣는 것이 마음에 들지 않으면, 조건문을 통해 다양하게 처리 하면 된다. (코드가 좀 지저분해지긴 하지만..)
let promise
.
.
.
{#await promise}
<h2>Loading...</h2>
{:then res}
{#if !res}
<div>없어 아무것도</div>
{:else}
<h1>{res}</h1>
{/if}
{/await}
다음은 데이터를 받아오는 동안 예외처리를 보자.
await
블록에 데이터를 받아오기 전 출력시킬 html을 작성한다.
{#await promise}
<h2>Loading...</h2>
{:then res}
<h1>{res}</h1>
{/await}
버튼을 누르자마자 Loading...
이 출력된다.
2초가 흐른 뒤 res
데이터를 받은 then
블록 쪽 html이 출력된다.
아래는 isError
값이 true
면 reject
가 호출되어 에러 객체의 메세지가 출력되도록 작성한 코드다.
catch 블럭
옆에 에러 발생시 에러 정보를 받아올 매개 변수를 받는다.
<script>
let isError = true
let promise = '초기값...'
function fetchName() {
return new Promise((resolve, reject) => {
if (isError) {
reject(new Error('에러 발생...'))
}
setTimeout(() => {
resolve('Jude')
}, 2000);
})
}
</script>
<button on:click={() => {
promise = fetchName()
}}>
Fetch name!
</button>
{#await promise}
<!-- 대기(Pending) -->
<h2>Loading...</h2>
{:then res}
<!-- 이행(Fulfilled) -->
<h1>{res}</h1>
{:catch error}
<!-- 거부(Rejected) -->
<h3>{error.message}</h3>
{/await}
<h3>에러 발생...<h3>
버튼을 클릭하자마자 에러 객체에서 메세지로 전달한 값이 출력된다.
로딩 처리와 에러 처리가 필요 없다면 아래와 같이 축약해서 작성할 수도 있다.
{#await promise then res}
<h1>{res}</h1>
{/await}
여기에 에러 처리만 추가 시키고자 하면 동일하게 catch
블럭을 추가하면 된다.
{#await promise then res}
<h1>{res}</h1>
{:catch error}
<h3>{error.message}</h3>
{/await}