迭代异步函数导致苗条

iterate over async function result in svelte

我正在尝试迭代某些异步函数返回的某些值。

import { onMount } from 'svelte';

let navigation;

onMount(async function(){
    navigation = FETCHER.data.navigation;
    console.log(navigation);
});

然后在 html

{#await navigation}
    {#each navigation.main as menuItem}
        foobar
    {/each}
{/await}

然而"foobar"从未曝光。

在导航中我找到了这个数据结构:

main: (3) […]
0: Object { ID: 16, url: "http://127.0.0.1/", title: "Welcome", … }
1: Object { ID: 15, url: "http://127.0.0.1/", title: "Home", … }
2: Object { ID: 176, url: "http://127.0.0.1/test/", title: "test", … }
length: 3

我真的很好奇为什么 await 块中的任何东西都没有被渲染。我是不是做错了什么承诺?

旁注中的一件事可能很重要:FETCHER.data.navigation 变量是使用 wp_localize_script 从 WordPress 传递过来的,因此没有任何 fetch 调用发出。

感谢您提前提出任何意见。

最好的, 塞博

await 的正确语法需要 then block:

{#await navigation}
    <p>awaiting...</p>
{:then navigation}
    {#each navigation.main as menuItem}
        foobar
    {/each}
{:catch error}
    <p>error</p>
{/await}

然而,这取决于 promise 正确解析的事实,并且在异步函数的情况下,需要 return 值。在此处的代码中,没有任何内容是从异步函数 return 编辑的,这将无法正确解析。

因此更正 await 块语法并return从 promise 中获取一个值,以下应该有效:

<script>
    import { onMount } from 'svelte';
    let promise;
    async function fetchStuff() {
        return FETCHER.data.navigation;
    }
    onMount(() => {
        promise = fetchStuff();
    });
</script>

{#await promise}
<p>
    awaiting...
</p>
{:then navigation}
<p>
    here access navigation
</p>
{:catch error}
<p>
    oh noes.
</p>
{/await}