Async

Abstraction for async operations that can be hooked into React.

Source code is hosted in GitHub

yarn add @corets/async

Seamless React integrations are shipped inside separate packages:

useAsyncuseStreamuseAction

createAsync()

Create an observable async operation:

import { createAsync } from "@corets/async"

const query = createAsync(async () => "some data")

Create an observable async operation without the factory function:

import { Async } from "@corets/async"

const query = new Async(async () => "some data")

Async.getResult()

Retrieve result from the last invocation:

query.getResult()

Async.getError()

Retrieve probable error from the last invocation:

query.getError()

Async.getState()

Retrieve all the details in a single call, contains values like isRunning, isCancelled, result, etc.:

query.getState()

Async.isRunning()

Check if the async operation is being executed right now:

query.isRunning()

Async.isCancelled()

Check if the latest async invocation has been cancelled:

query.isCancelled()

Async.isErrored()

Check if the latest async invocation errored:

query.isErrored()

Async.run()

Invoke async operation:

import { createAsync } from "@corets/async"

const query = createAsync(async (argument: number) => "some data")
const queryWithArguments = createAsync(async (argument: number) => `The value is ${argument}`)

const result = await query.run()
const anotherResult = await queryWithArguments.run(1337)

Async.resolve()

Manually resolve async result, makes it available on the instance using getResult():

import { createAsync } from "@corets/async"

const query = createAsync(async (argument: number) => "some data")

const resultFromValue = await query.resolve("another value")
const resultFromPromise = await query.resolve(Promise.resolve("another value"))
const resultFromProducer = await query.resolve(async () => "another value")

Async.cancel()

Cancel current async invocation:

query.cancel()

Async.listen()

Subscribe to state changes, the listener receives the same object that you get from getState():

const unsubscribe = query.listen((state) => console.log("async state changed", state))

Last updated