npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

promise-state-js

v1.0.1

Published

Immutable snapshot representation of es6 promise

Downloads

5

Readme

promise-state-js

Immutable snapshot representation of es6 promise

Install

yarn add promise-state-js

or

npm install --save promise-state-js

Examples

React hooks example (Typescript)

import {useState} from "react";
import PromiseState from 'promise-state-js';

function UserDetails() {
    const [state, setState] = useState<PromiseState<User>>(null);
    
    useEffect(function initialize() {
        PromiseState.subscribe(fetch('/users'), setState);       
    }, []);
    
    return state?.fold({
        pending: () => <div>Loading user info...</div>,
        rejected: () => <div>Failed to load user</div>,
        resolved: user => <div>
            <div>Name: {user.name}</div>
            <div>Email: {email.name}</div>
        </div>, 
    });

}

Redux+Thunk example (Typescript)

import PromiseState from 'promise-state-js';
import { ThunkDispatch } from 'redux-thunk';

const FETCH_USERS = 'FETCH_USERS';
const loadUser = () => (dispatch: ThunkDispatch) =>
    PromiseState.subscribe(fetch('/users'), state =>
        dispatch({ type: FETCH_USERS, state }));

function userReducer(state = null, action): PromiseState<User> {
  if(action.type === FETCH_USERS)
      return action.state;
  return state;
}

Async/await

You can subscribe to a promise, as well as to an async function e.g.:

PromiseState.subscribe(async function() {
    const login = await fetch('/current-login');
    return login ?? fetch(`/user/${login.userId}`);
}, setState);

Usage

import PromiseState from 'promise-state-js';

Create instance

You can create instance through one of these:

const resolved = PromiseState.resolve({ name: 'bob' });
const rejected = PromiseState.reject(Error(''));
const pending = PromiseState.pending;

PromiseState is immutable by design. Once instantiated there is no way to change its state.

Instance properties

isResolved

Boolean. True if the instance object has resolved status.

isRejected

Boolean. True if the instance object has rejected status.

isFulfilled

Boolean. True if the instance object has resolved or rejected status.

isPending

Boolean. True if the instance object has pending status.

value

R | void. Obtains the value of resolved promise, else undefined.

error

R | void. Obtains error value of rejected promise, else undefined.

Instance methods

then

map<T>(mapper: (r: R) => T): PromiseState<T>
Allows to map over a value stored inside PromiseState object. Mapper applied only to successive instances. Returns the new PromiseState object with transformed value inside.

PromiseState
  .resolve(10)
  .then(x => x + 5, handleError)
  .value; // => 15

You can also return another PromiseState instance from the mapper function, i.e.:

PromiseState
  .resolve(10)
  .then(x => x >= 0 ? x : PromiseState.reject(Error('negative value')))
  .value; // => 15

fold

fold<T>(folder: Folder<R, T>): T | null
Fold receives object (Folder) that specifies different actions for different PromiseState states. Useful to applying side effects and reduce boilerplate code.

promiseState.fold({
        pending: () => <div>Loading user info...</div>,
        rejected: () => <div>Failed to load user</div>,
        resolved: user => <div>
            <div>Name: {user.name}</div>
            <div>Email: {email.name}</div>
        </div>, 
    });

get

get(): R
Extract the value from PromiseState if resolved, or throw if pending/rejected.

PromiseState
  .resolve(10)
  .get(); // => 15

PromiseState
  .reject(Error('Some error'))
  .get(); // => throws

Composition

PromiseState class has two static methods for composing many instances together. API pretty similar to PromiseState.all and PromiseState.race methods.

all

all(p1: PromiseState<P1>, p2: PromiseState<P2>, ...): PromiseState<[P1, P2, ...]> If all items are resolved then will return a PromiseState containing an array of all the resolved items. Else will return pending or rejected.

PromiseState.all(
  PromiseState.resolve(42),
  PromiseState.resolve('foo')
).value; // == [42, 'foo']

race

race(p1: PromiseState<P1>, p2: PromiseState<P2>, ...): PromiseState<P1|P2|...>
Returns first fulfilled outcome (resolved or rejected). If there are no complete items then will return the first item from arguments. If arguments empty will return undefined.

PromiseState.race(
  PromiseState.pending,
  PromiseState.resolve(42),
  PromiseState.resolve('foo')
).value; // == 42