我有几个 Svelte 组件和一个自定义可写存储。店里有一个init
函数是async
并用一些 REST API 的数据库表的数据填充存储的值。我的组件都必须使用自动订阅来订阅该商店。订阅时,init
必须被调用。总体思路是在数据库上实现 CRUD 操作,在存储上实现 CRUD 操作(有助于显示存储的值,i.e.数据库的表,具有反应性)。
As init
is async
因此,返回一个承诺,我需要await
它在我的组件中。但由于我使用自动订阅(通过在商店名称前加上前缀)$
), 我怎样才能做到这一点?
例如:App.svelte
(组件):
<script>
import { restaurant_store } from './Restaurant.js'
export let name
</script>
<main>
<!--- I need to handle the promise and rejection here -->
{#each $restaurant_store as restaurant}
<li>
{restaurant.name}
</li>
{/each}
</main>
Restaurant.js
(商店):
import { writable } from 'svelte/store'
export function createRestaurantsStore() {
const { subscribe, update } = writable({ collection: [] })
return {
subscribe,
init: async () => {
const response = await fetch('http://localhost:1337/restaurants')
if(response.ok) {
const json_response = await response.json()
set({ collection: json_response })
return json_response
}
throw Error(response.statusText)
},
insert: async (restaurant) => {
const response = await fetch('http://localhost:1337/restaurants', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(restaurant)
})
if(response.ok) {
const json_response = await response.json()
update(store_state => store_state.collection.push(json_response))
return json_response
}
throw Error(response.statusText)
},
update: async (restaurant, id) => {
const response = await fetch('http://localhost:1337/restaurants/' + id, {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(restaurant)
})
if(response.ok) {
const json_response = await response.json()
update(store_state => {
const current_id = store_state.collection.findIndex(e => e.id === id)
store_state.collection.splice(current_id, 1, json_response)
})
return json_response
}
throw Error(response.statusText)
}
}
}
export const restaurant_store = createRestaurantsStore()