如何 return 将存储作为 promise 而不是带有订阅的对象

how to return svelte store as promise instead of an object with subscribe

我有一个像这样的苗条商店取自 this example:

store.ts

import { writable } from 'svelte/store';

export const count = writable(0);

test.svelte

function increment() {
    count.update(n => n + 1);
}

我可以这样得到值:

app.svelte

const unsubscribe = count.subscribe(value => {
    count_value = value;
});

但是是否可以使用 await / Promise 而不是带有订阅的类似可观察对象的对象来 一次 获取值?

示例:

const count-value = await count.toPromise();

显然 toPromise 不存在于 Writable 对象上,但我想也许可以通过 rxjs, internal svelte,或 wonka 可能会有一个选项或某种解决方法。

我不知道 Svelte 商店有任何承诺 API。如果只想获取一次值,可以使用get.

import { get } from 'svelte/store';

const countValue = get(count);

虽然在热代码路径中不推荐这样做。来自文档:

This works by creating a subscription, reading the value, then unsubscribing. It's therefore not recommended in hot code paths.

你也可以这样写:

import { writable } from 'svelte/store';

const count = writable(0);

function increment() {
    $count += 1;
    console.log($count);
};

increment();

或与 setContext 和 getContext 共享一个计数器

counter.svelte:

  import { setContext } from 'svelte';

  let count = 10;
  setContext('counter', {
    get count() {return count},
    increment: () => {count += 1},
    getCount: async () => {return await count} 
  });

increment.svelte:

import { setContext } from 'svelte';

const counter = getContext('counter');
counter.increment();

getters.svelte:

import { getContext } from 'svelte';

const counter = getContext('counter');
console.log(counter.count);
counter.getCount().then((c) => console.log(c));