您所做的实际上不是从承诺中返回数据,而只是返回成功状态,即您将数据本身保存到单独的变量中:
let things = []
async function getThings(){
const res = await fetch(`https://jsonplaceholder.typicode.com/users`);
const json = await res.json();
if (res.ok) {
// save the result to json
things = json;
// you can even leave this part out
return true;
} else {
throw new Error(text);
}
}
那么当 promise 解决时,你当然会循环遍历数组:
{#await promise}
<p>...waiting</p>
{:then success}
{#each things as thing, index (thing.id)}
stuff goes here
{/each}
{/await}
最后在你的删除函数中你现在可以操作数组了:
function onDelete(id) {
things = things.filter(t => t.id != id)
}
另一种方法是将获取数据与显示数据分开,使其成为两个不同的组件:
{#await promise}
<p>...waiting</p>
{:then things}
<DisplayComponent data={things} />
{/await}
在DisplayComponent 内部,您的数据现在将位于一个常规数组中,您可以对它做任何您想做的事情。这样做的一个好处是您可以通过发送模拟数据来独立测试DisplayComponent。