1.2.2 • Published 7 months ago

dyna-sync v1.2.2

Weekly downloads
5
License
MIT
Repository
-
Last release
7 months ago

dyna-sync - Synchronize async function calls and promises

syncFunctions

Synchronizes async methods

TS type: syncFunctions = (...functions: Array<((next?: any) => void) | undefined | null>): void

Usage

As arguments, pass the functions with 1st arg a callback to proceed the next.

The callback argument is optional.

Example

import {syncFunctions} from "dyna-sync";

syncFunctions(

  next => setTimeout(() => {
    output.push('First');
    next();
  }, 100),

  next => setTimeout(() => {
    output.push('Second');
    next(undefined);
  }, 500),

  () => output.push('Third'),
  () => undefined,

  () => {
    expect(output.join()).toBe('First,Second,Third');
    testDone();
  },
);

Use in React

The syncFunctions is ideal for squential React's setState() calls.

In react, you cannot call the setState() on next the other because the last will override the changes of the previous since the setState() is async!.

You cannot do this!

Let's say that at this point this.state.firstName==='' and this.state.lastName===''

  this.setState({firstName: 'John'});
  this.setState({lastname: 'Smith'});  

What we have now on state is this.state.firstName==='' and this.state.lastName==='Smith'

The firstName is still an empty string, since the 2nd call overrides the first sync call.

You can solve this like this with syncFunctions

syncFunctions(
  next => this.setState({firstName: 'John'}, next);
  next => this.setState({lastname: 'Smith'}, next);
);  

What we have now on state is this.state.firstName==='John' and this.state.lastName==='Smith'.

This happens because setState's 2nd argument of React is a callback called when the state is updated.

The 2nd function of the syncFunctions is called only when next of the 1st function is called.

syncPromises

Synchronizes async Promises

The syncPromises is working like the Promise.all, it returns an array with the resolved items but is calls the promises synchronously.

TS type: syncPromises = <TResolve = any, >(...promisedFunctions_: Array<(() => Promise<TResolve>)>): Promise<TResolve[]>

Usage

Example with calls

import {syncPromises} from "dyna-sync";

syncPromises(
  () => fetch('http://api.example.com/metadata').then(updateMetadata),
  () => fetch('http://api.example.com/users').then(updateUsers),
)

The updateUsers if the 2nd promise is called only when the 1st promise is resolved.

Example with output and typesript

import {syncPromises} from "dyna-sync";

syncPromises<IUsers>(
  () => fetch('http://api.example.com/users/section/support'),  // Suppose that returns array of users
  () => fetch('http://api.example.com/users/section/billing'),  // Suppose that returns array of users
)
    .then((resultUsers: Users[][]) => [].concat(resultUsers))

When the above syncPromises is resolved, it will return an array of two items since we have two promises. It is precisely like the Promise.all with the difference that one promise is executed each time in a row.

If each of the above promises returns an array of users, then we have an array of two arrays of users.

syncPromisesResilience

The syncPromisesResilience is working like the syncPromises but it doesn't break on errors.

TS type:

type PromiseResult<TData> =
  | { data: TData }
  | { error: Error };
syncPromisesResilience = 
  async <TData, >(promisedFunctions: Array<() => Promise<TData>>): 
    Promise<Array<PromiseResult<TData>>>

As argument, it gets an array (instead of arguments array) and it returns array of two types of objects:

  • The {data: TData} or
  • the {error: Error}

Usage

const results = await syncPromisesResilience<{ name: string }>(
  [
    () => fetch({customerId: '8745924'}),
    () => fetch({customerId: '4859623'}),
    () => fetch({customerId: '6927464'}),
    () => fetch({customerId: '0385633'}),
    () => fetch({customerId: '5893244'}),
  ]
);

Output example

  [
    Object {
      "data": Object {
        "name": "Joihn Smith",
      },
    },
    Object {
      "data": Object {
        "name": "Nora Jones",
      },
    },
    Object {
      "data": Object {
        "name": "Christofer Lee",
      },
    },
    Object {
      "error": [Error: General load error], // Here we have an error property, instead of data
    },
    Object {
      "data": Object {
        "name": "Monica Williams",
      },
    },
  ]
1.2.2

7 months ago

1.2.1

7 months ago

1.1.1

1 year ago

1.1.2

1 year ago

1.0.1

3 years ago

0.0.2

3 years ago