Svelte:如何处理组件中自定义可写存储的异步初始化承诺? [英] Svelte: How to handle the custom writtable store's async init's promise in the component?

查看:12
本文介绍了Svelte:如何处理组件中自定义可写存储的异步初始化承诺?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个Svelte组件和一个定制的可写存储。存储有一个init函数,它是async,它用一些rest API的数据库的表数据填充存储的值。我的组件都必须使用自动订阅来订阅此存储。订阅时,必须调用init。全局思想是在数据库上实现CRUD操作,在存储上执行CRUD操作(用于显示存储的值,数据库的表,并具有反应性)。

由于initasync,因此返回一个承诺,我需要在我的组件中.then .catch它。但由于我使用自动订阅(通过在商店名称前加上$),我如何才能做到这一点?

例如: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()

推荐答案

Svelte提供了一个built-in mechanism来处理模板中承诺的可能状态,因此相同的状态可能如下所示:

<main>
    {#await restaurant_store.init()}
        <p>waiting for the promise to resolve...</p>
    {:then}
      {#each $restaurant_store as restaurant}
        <li>
          {restaurant.name}
        </li>
      {/each}
    {:catch error}
        <p>Something went wrong: {error.message}</p>
    {/await}
</main>

查看REPL以获取实时示例。

这篇关于Svelte:如何处理组件中自定义可写存储的异步初始化承诺?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆