简体   繁体   English

如何通过异步 function 使用 Svelte 的反应性

[英]How to use Svelte's reactivity with an async function

I want to display a list of data that I read (asynchronously) from files我想显示我从文件中(异步)读取的数据列表

The following emulates what I am trying to achieve REPL以下模拟了我正在尝试实现的REPL

<h1>Test array</h1>

{#each my_list as item}
    <div>{item}</div>
{/each}

<script>
    let started = false;
    let my_list = [];
    let param = 0;
    $: my_list = analyseData(param);
    
    setTimeout(function(){
        param = 1;
    }, 5000);
    
function analyseData() {
    if (!started) {
        started = true;
        return [0];
    }
    // read files asynchronously here
        return [1, 2, 3];
}
</script>

But, of course, the function analyseData needs to be async, and as soon as I change to但是,当然,function analyseData需要是异步的,一旦我更改为

async function analyseData() { 
...

it no longer works.它不再起作用了。 What is the solution?解决办法是什么?

Svelte implements an Await Block for just this purpose. Svelte 实现了一个等待块就是为了这个目的。

Long hand including catch for your example would be:对于您的示例,包括 catch 在内的长手将是:

{#await my_list}
    <p>...waiting</p>
{:then resolved_list}
    {#each resolved_list as item}
        <div>{item}</div>
    {/each}
{:catch error}
    <p style="color: red">{error.message}</p>
{/await}

Or since your example will never reject you can use the shorthand:或者由于您的示例永远不会拒绝,您可以使用速记:

{#await my_list then resolved_list}
    {#each resolved_list as item}
        <div>{item}</div>
    {/each}
{/await}

REPL REPL

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM