Skip to content

Documentation / @warp-drive/ember / getPromiseState

Function: getPromiseState()

ts
function getPromiseState<T, E>(promise): Readonly<PromiseState<T, E>>;

Defined in: warp-drive-packages/core/declarations/store/-private/new-core-tmp/promise-state.d.ts:261

Returns a reactive state-machine for the provided promise or awaitable.

Repeat calls to getPromiseState with the same promise will return the same state object making is safe and easy to use in templates and JavaScript code to produce reactive behaviors around promises.

getPromiseState can be used in both JavaScript and Template contexts.

ts
import { getPromiseState } from '@warp-drive/ember';

const state = getPromiseState(promise);

For instance, we could write a getter on a component that updates whenever the promise state advances or the promise changes, by combining the function with the use of @cached

ts
class Component {
  @cached
  get title() {
    const state = getPromiseState(this.args.request);
    if (state.isPending) {
      return 'loading...';
    }
    if (state.isError) { return null; }
    return state.result.title;
  }
}

Or in a template as a helper:

gjs
import { getPromiseState } from '@warp-drive/ember';

<template>
  {{#let (getPromiseState @request) as |state|}}
    {{#if state.isPending}} <Spinner />
    {{else if state.isError}} <ErrorForm @error={{state.error}} />
    {{else}}
      <h1>{{state.result.title}}</h1>
    {{/if}}
  {{/let}}
</template>

If looking to use in a template, consider also the <Await /> component.

See also PromiseState

Type Parameters

T

T = unknown

E

E = unknown

Parameters

promise

Promise<T> | Awaitable<T, E>

Returns

Readonly<PromiseState<T, E>>

Released under the MIT License.