Skip to content

AsyncHelpers

import: @azure-net/kit

AsyncHelpers returns an object with two methods:

  • createAsyncAction - assumes POST, PUT, DELETE, PATCH methods
  • createAsyncResource - assumes GET method

They return responses differently and have a considerable set of settings.

First let's look at the direct implementation, and then at the detailed settings.

typescript
import { createAsyncHelpers } from '@azure-net/kit';

// I consider it important to remind you that this method accepts an object with a parseError key
// You can pass errorParser from the previous block to this key, there is also an example there
const { createAsyncAction, createAsyncResource } = createAsyncHelpers();

// error in AppError format, success - whether the method executed successfully, response - the response accordingly.
// createAsyncAction accepts a callback and expects it to return a Promise
const { success, response, error } = await createAsyncAction(() => SomePromiseFunc());

// Returns the response directly, also accepts a callback and expects it to return a Promise
const resource = await createAsyncResource(() => SomePromiseFunc());

As a second argument after the callback, both createAsyncResource and createAsyncAction accept an object with settings

typescript
const createAsyncAction = <Res = unknown, Req = unknown>(
    action: ActionOrThunk<Res>,
    args?: {
        // Happens right before calling action or resource, execution stops and will not continue until next is called
        beforeSend?: (next: () => void, abort: () => void) => void | Promise<void>;
        // Will happen on successful request execution, provides access to the response in the callback
        // What you return is ignored, return simply interrupts execution.
        onSuccess?: (result: AsyncActionResponse<Res, undefined, Custom>) => Promise<unknown> | unknown;
        // Will happen if the request was unsuccessful. Also ignores your return, gives access to error
        onError?: (result: AsyncActionResponse<never, Req, Custom>) => Promise<unknown> | unknown;
        // Responsible for whether the fallback response will be returned or throw Error will occur (if true)
        reject?: boolean;
        // condition - under what condition the request will be aborted, onAbort - what will happen after abort
        abort?: {
            condition: boolean;
            onAbort?: () => void;
        };
        // Response fallback, if the request failed will return it as the response, if reject === false
        fallbackResponse?: Res;
    }
): Promise<AsyncActionResponse<Res, Req, Custom>> => {}

The settings are the same for both createAsyncResource and createAsyncAction. An important point is that AsyncHelpers work with schemas from the package and in case of validation error they will process and return errors (about schemas in the block below).

Example

typescript
// The json method will automatically force the schema to validate before the request, if validation fails, you will get schema errors in the error.fields key
const create = async (request: Partial<IScriptCreateRequest>) =>
    await createAsyncAction<IScript, IScriptCreateRequest>(ScriptService.create(CreateScriptSchema.from(request).json()), {
        onSuccess: () => {
            successNotification('shared.notifications.created');
        }
    });