• Stars
    star
    205
  • Rank 191,264 (Top 4 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 8 years ago
  • Updated 8 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Asynchronous Programming Library for JavaScript & Node.js

Asynchronous Programming Library

ci status snyk npm version npm downloads/month npm downloads license

Installation

$ npm install metasync

Asynchronous functions composition

metasync(fns)(data, done)

  • fns - array of callback-last functions, callback contranct err-first
  • data - input data (optional)
  • done - err-first callback
  • Returns: composed callback-last / err-first function

composition

const composed = metasync([f1, f2, f3, [[f4, f5, [f6, f7], f8]], f9]);
  • Array of functions gives sequential execution: [f1, f2, f3]
  • Double brackets array of functions gives parallel execution: [[f1, f2, f3]]

Example:

const metasync = require('metasync');
const fs = require('fs');

// Data collector (collect keys by count)
const dc = metasync.collect(4);

dc.pick('user', { name: 'Marcus Aurelius' });
fs.readFile('HISTORY.md', (err, data) => dc.collect('history', err, data));
dc.take('readme', fs.readFile, 'README.md');
setTimeout(() => dc.pick('timer', { date: new Date() }), 1000);

// Key collector (collect certain keys by names)
const kc = metasync
  .collect(['user', 'history', 'readme', 'timer'])
  .timeout(2000)
  .distinct()
  .done((err, data) => console.log(data));

kc.pick('user', { name: 'Marcus Aurelius' });
kc.take('history', fs.readFile, 'HISTORY.md');
kc.take('readme', fs.readFile, 'README.md');
setTimeout(() => kc.pick('timer', { date: new Date() }), 1000);

API

callbackify(fn)

Returns: <Function>

Convert Promise-returning to callback-last / error-first contract

asyncify(fn)

Returns: <Function> with contract: callback-last / error-first

Convert sync function to callback-last / error-first contract

promiseToCallbackLast(promise, callback)

Convert Promise to callback-last

promisify(fn)

Returns: <Function> Promise-returning function

Convert async function to Promise-returning function

promisifySync(fn)

Returns: <Function> Promise-returning function

Convert sync function to Promise object

map(items, fn, done)

Asynchronous map (iterate parallel)

filter(items, fn, done)

Asynchrous filter (iterate parallel)

Example:

metasync.filter(
  ['data', 'to', 'filter'],
  (item, callback) => callback(item.length > 2),
  (err, result) => console.dir(result),
);

reduce(items, fn, done[, initial])

  • items: <Array> incoming
  • fn: <Function> to be executed for each value in array
    • previous: <any> value previously returned in the last iteration
    • current: <any> current element being processed in the array
    • callback: <Function> callback for returning value back to reduce function
    • counter: <number> index of the current element being processed in array
    • items: <Array> the array reduce was called upon
  • done: <Function> on done
  • initial: <any> optional value to be used as first argument in first iteration

Asynchronous reduce

reduceRight(items, fn, done[, initial])

  • items: <Array> incoming
  • fn: <Function> to be executed for each value in array
    • previous: <any> value previously returned in the last iteration
    • current: <any> current element being processed in the array
    • callback: <Function> callback for returning value back to reduce function
    • counter: <number> index of the current element being processed in array
    • items: <Array> the array reduce was called upon
  • done: <Function> on done
  • initial: <any> optional value to be used as first argument in first iteration

Asynchronous reduceRight

each(items, fn, done)

Asynchronous each (iterate in parallel)

Example:

metasync.each(
  ['a', 'b', 'c'],
  (item, callback) => {
    console.dir({ each: item });
    callback();
  },
  (err, data) => console.dir('each done'),
);

series(items, fn, done)

Asynchronous series

Example:

metasync.series(
  ['a', 'b', 'c'],
  (item, callback) => {
    console.dir({ series: item });
    callback();
  },
  (err, data) => {
    console.dir('series done');
  },
);

find(items, fn, done)

Asynchronous find (iterate in series)

Example:

metasync.find(
  [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16],
  (item, callback) => callback(null, item % 3 === 0 && item % 5 === 0),
  (err, result) => {
    console.dir(result);
  },
);

every(items, fn, done)

Asynchronous every

some(items, fn, done)

Asynchronous some (iterate in series)

asyncMap(items, fn[, options][, done])

Non-blocking synchronous map

asyncIter(base)

Returns: <AsyncIterator>

Create an AsyncIterator instance

class AsyncIterator

AsyncIterator.prototype.constructor(base)

async AsyncIterator.prototype.next()

async AsyncIterator.prototype.count()

async AsyncIterator.prototype.each(fn, thisArg)

async AsyncIterator.prototype.forEach(fn, thisArg)

async AsyncIterator.prototype.parallel(fn, thisArg)

async AsyncIterator.prototype.every(predicate, thisArg)

async AsyncIterator.prototype.find(predicate, thisArg)

async AsyncIterator.prototype.includes(element)

async AsyncIterator.prototype.reduce(reducer, initialValue)

async AsyncIterator.prototype.some(predicate, thisArg)

async AsyncIterator.prototype.someCount(predicate, count, thisArg)

async AsyncIterator.prototype.collectTo(CollectionClass)

async AsyncIterator.prototype.collectWith(obj, collector)

async AsyncIterator.prototype.join(sep = ', ', prefix = '', suffix = '')

async AsyncIterator.prototype.toArray()

AsyncIterator.prototype.map(mapper, thisArg)

AsyncIterator.prototype.filter(predicate, thisArg)

AsyncIterator.prototype.flat(depth = 1)

AsyncIterator.prototype.flatMap(mapper, thisArg)

AsyncIterator.prototype.zip(...iterators)

AsyncIterator.prototype.chain(...iterators)

AsyncIterator.prototype.take(amount)

AsyncIterator.prototype.takeWhile(predicate, thisArg)

AsyncIterator.prototype.skip(amount)

AsyncIterator.prototype.throttle(percent, min)

AsyncIterator.prototype.enumerate()

collect(expected)

Returns: <Collector>

Create Collector instance

class Collector

Data collector

Collector.prototype.constructor(expected)

Data collector

Collector.prototype.collect(key, err, value)

Returns: <this>

Pick or fail key

Collector.prototype.pick(key, value)

Returns: <this>

Pick key

Collector.prototype.fail(key, err)

Returns: <this>

Fail key

Collector.prototype.take(key, fn, args)

Returns: <this>

Take method result

Collector.prototype.timeout(msec)

Returns: <this>

Set timeout

Collector.prototype.done(callback)

Returns: <this>

Set on done listener

Collector.prototype.finalize(key, err, data)

Collector.prototype.distinct(value)

Returns: <this>

Deny or allow unlisted keys

Collector.prototype.cancel(err)

Collector.prototype.then(fulfill, reject)

compose(flow)

Returns: <Function> composed callback-last / err-first

Asynchronous functions composition

Array of functions results in sequential execution: [f1, f2, f3] Double brackets array of functions results in parallel execution: [[f1, f2, f3]]

Example:

const composed = metasync([f1, f2, f3, [[f4, f5, [f6, f7], f8]], f9]);

class Composition

Composition.prototype.constructor()

Composition.prototype.on(name, callback)

Composition.prototype.finalize(err)

Composition.prototype.collect(err, result)

Composition.prototype.parallel()

Composition.prototype.sequential()

Composition.prototype.then(fulfill, reject)

Composition.prototype.clone()

Clone composed

Composition.prototype.pause()

Pause execution

Composition.prototype.resume()

Resume execution

Composition.prototype.timeout(msec)

Set timeout

Composition.prototype.cancel()

Cancel execution where possible

firstOf(fns, callback)

Executes all asynchronous functions and pass first result to callback

parallel(fns[, context], callback)

Parallel execution

Example:

metasync.parallel([f1, f2, f3], (err, data) => {});

sequential(fns[, context], callback)

Sequential execution

Example:

metasync.sequential([f1, f2, f3], (err, data) => {});

runIf(condition[, defaultVal], asyncFn, ...args)

  • condition: <any>
  • defaultVal: <any> optional, value that will be returned to callback if condition is falsy.
  • asyncFn: <Function> callback-last function that will be executed if condition if truthy
  • args: <any[]> args to pass to asyncFn

Run asyncFn if condition is truthy, else return defaultVal to callback.

runIfFn(asyncFn, ...args)

  • asyncFn: <Function> callback-last function that will be executed if it is provided
  • args: <any[]> args to pass to asyncFn

Run asyncFn if it is provided

class do

do.prototype.constructor(fn, ...args)

toAsync(fn)

Returns: <Function>

Convert synchronous function to asynchronous

Transform function with args arguments and callback to function with args as separate values and callback

asAsync(fn, args)

Wrap function adding async chain methods

of(args)

Applicative f => a -> f a

concat(fn1, fn2)

Monoid m => a -> a -> a

fmap(fn1, f)

Functor f => (a -> b) -> f a -> f b

ap(fn, funcA)

Applicative f => f (a -> b) -> f a -> f b

memoize(fn)

Returns: <Function> memoized

Create memoized function

class Memoized

Memoized.prototype.constructor()

Memoized.prototype.clear()

Memoized.prototype.add(key, err, data)

Memoized.prototype.del(key)

Memoized.prototype.get(key, callback)

Memoized.prototype.on(eventName, listener)

Add event listener

Example:

const memoized = new Memoized();
memoized.on('memoize', (err, data) => { ... });
memoized.on('add', (key, err, data) => { ... });
memoized.on('del', (key) => { ... })
memoized.on('clear', () => { ... });

Memoized.prototype.emit(eventName, args)

  • eventName: <string>
  • args: <any> rest arguments

Emit Memoized events

poolify(factory, min, norm, max)

queue(concurrency)

  • concurrency: <number> simultaneous and asynchronously executing tasks

Returns: <Queue>

Create Queue instance

class Queue

Queue constructor

Queue.prototype.constructor(concurrency)

  • concurrency: <number> asynchronous concurrency

Queue constructor

Queue.prototype.wait(msec)

  • msec: <number> wait timeout for single item

Returns: <this>

Set wait before processing timeout

Queue.prototype.throttle(count[, interval])

  • count: <number> item count
  • interval: <number> per interval, optional default: 1000 msec

Returns: <this>

Throttle to limit throughput

Queue.prototype.add(item[, factor[, priority]])

Returns: <this>

Add item to queue

Queue.prototype.next(task)

  • task: <Array> next task [item, factor, priority]

Returns: <this>

Process next item

Queue.prototype.takeNext()

Returns: <this>

Prepare next item for processing

Queue.prototype.pause()

Returns: <this>

Pause queue

This function is not completely implemented yet

Queue.prototype.resume()

Returns: <this>

Resume queue

This function is not completely implemented yet

Queue.prototype.clear()

Returns: <this>

Clear queue

Queue.prototype.timeout(msec, onTimeout)

Returns: <this>

Set timeout interval and listener

Queue.prototype.process(fn)

Returns: <this>

Set processing function

Queue.prototype.done(fn)

Returns: <this>

Set listener on processing done

Queue.prototype.success(listener)

Returns: <this>

Set listener on processing success

Queue.prototype.failure(listener)

Returns: <this>

Set listener on processing error

Queue.prototype.drain(listener)

Returns: <this>

Set listener on drain Queue

Queue.prototype.fifo()

Returns: <this>

Switch to FIFO mode (default for Queue)

Queue.prototype.lifo()

Returns: <this>

Switch to LIFO mode

Queue.prototype.priority(flag)

  • flag: <boolean> default: true, false will disable priority mode

Returns: <this>

Activate or deactivate priority mode

Queue.prototype.roundRobin(flag)

  • flag: <boolean> default: true, false will disable roundRobin mode

Returns: <this>

Activate or deactivate round robin mode

Queue.prototype.pipe(dest)

Returns: <this>

Pipe processed items to different queue

throttle(timeout, fn, ...args)

Returns: <Function>

Get throttling function, executed once per interval

debounce(timeout, fn, ...args)

Debounce function, delayed execution

timeout(timeout, fn, callback)

Set timeout for asynchronous function execution

Contributors

More Repositories

1

impress

Enterprise application server for Node.js and Metarhia private cloud ⚡
JavaScript
969
star
2

Example

Metarhia application example for Node.js 🟢
JavaScript
198
star
3

jstp

Fast RPC for browser and Node.js based on TCP, WebSocket, and MDSF
JavaScript
142
star
4

noroutine

Goroutine analogue for Node.js, spreads I/O-bound routine calls to utilize thread pool (worker_threads) using balancer with event loop utilization. 🌱
JavaScript
120
star
5

metautil

Metarhia utilities 🧰
JavaScript
98
star
6

web-locks

Web Locks API 🔒
JavaScript
83
star
7

Docs

Metarhia docs and F.A.Q. 📒
82
star
8

metacom

RPC communication protocol for Metarhia stack 🔌
JavaScript
80
star
9

BestPractice

Metarhia best practice for relative technologies
62
star
10

common

Metarhia Common Library 🗜️
JavaScript
62
star
11

Metarhia

Technology Stack for Highload Applications ⬢
HTML
61
star
12

globalstorage

Distributed Data Warehouse 🌍
JavaScript
60
star
13

swayer

Schema based frontend framework 👀
JavaScript
52
star
14

metaschema

Schema definition and validation 💡
JavaScript
52
star
15

sandboxed-fs

Sandbox wrapper for Node.js File System API 💾
JavaScript
47
star
16

concolor

Colouring template strings using tags with annotations 🎨
JavaScript
44
star
17

do

Simplest way to manage asynchronicity
JavaScript
43
star
18

metarhia.com

Metarhia technology stack web site ⬢
JavaScript
40
star
19

metalog

Metarhia logger 📝
JavaScript
40
star
20

metasql

Metarhia SQL builder and Postgres utilities 🐘
JavaScript
40
star
21

metavm

Script loader with isolated sandboxes for node.js 📦
JavaScript
39
star
22

Contracts

Metarhia core docs and contracts specifications 📒
37
star
23

tickplate

Back-tick template engine for JavaScript 💬
JavaScript
33
star
24

arhaica

Milti-Domain Content Publishing System for Archaic Web
JavaScript
32
star
25

Manifesto

Manifesto of Metarhia Community ⬢
29
star
26

messenger

JavaScript
29
star
27

impress-cli

Impress Application Server Command line interface
JavaScript
28
star
28

console

Constructivism in UI rendering
26
star
29

JSQL

JavaScript Query Language
JavaScript
25
star
30

impress-example

Example application for Impress Application Server
JavaScript
23
star
31

eslint-config-metarhia

ESLint config for Metarhia projects
JavaScript
18
star
32

metatests

Extremely simple to use test framework and runner for Metarhia technology stack 🧪
JavaScript
18
star
33

metawatch

Nested directories watch for node.js 🕵️
JavaScript
14
star
34

metaconfiguration

Metarhia configuration loader 🔧
JavaScript
14
star
35

SummerCamp

Metarhia Summer Camp 2022
12
star
36

metastreams

Readable and Writable Streams with buffering
JavaScript
12
star
37

lowscript

Low-code script engine for Metarhia 📃
JavaScript
11
star
38

Metapay

Metarhia payment subsystem 🪙
11
star
39

sql

Metarhia SQL utilities
JavaScript
11
star
40

metadomain

Metarhia core model: database schemas 💎
JavaScript
10
star
41

metadoc

Metarhia Documentation Generator
JavaScript
10
star
42

metacalc

Spreadsheet calculations for Metarhia 🧮
JavaScript
10
star
43

Template

Metarhia app minimal template 🔵
JavaScript
9
star
44

mdsf

Metarhia Data Serialization Format
C++
9
star
45

Roadmap

Roadmap for new contributors and for technology stack 🛣️
9
star
46

Metalocal

Smart local area, township, housing, city solution 🏘️
9
star
47

jstp-swift

Swift
9
star
48

Accounts

User accounts, contacts, permissions, and authentication subsystem 👥
8
star
49

metamail

Metarhia mail subsystem ✉️
JavaScript
8
star
50

metacom-android

Metacommunicator for Android
Java
8
star
51

metacms

Metarhia CMS
JavaScript
8
star
52

iterator

Efficient and composable iteration
JavaScript
8
star
53

filestorage

JavaScript
8
star
54

protocol

Metarhia Protocol
Shell
8
star
55

tools

Metarhia development tools
JavaScript
7
star
56

Metanet

Communication, messaging, file transfer and content publishing 🔭
7
star
57

console-web

Metarhia web client
JavaScript
7
star
58

MetaTalk

Metarhia application example: chat, file storage, auth
JavaScript
7
star
59

metagram

ERD generator for metaschema
JavaScript
7
star
60

metatests-browser-runner

Browser test runner for metatests ⚙️
JavaScript
7
star
61

eslint-plugin-impress

ESLint plugin for Impress Application Server
JavaScript
6
star
62

xxii

xxii news
JavaScript
6
star
63

metacom-ios

Metacommunicator for iOS
Swift
6
star
64

jstp-java

JSTP implementation in java
Java
5
star
65

metascheduler

Metarhia task scheduler 📅
JavaScript
5
star
66

metaschema-langserver

Metaschema Language Server Protocol
5
star
67

metastorage

Metarhia file storage
JavaScript
5
star
68

metagui

GUI Components for Metarhia technology stack
JavaScript
5
star
69

remark-preset-lint-metarhia

Opinionated remark-lint preset
JavaScript
5
star
70

metacommand

Metarhia command-line interface utilities
JavaScript
5
star
71

mtypes

Common types for Metarhia 🤝
JavaScript
5
star
72

Partners

Metarhia (NodeUA and HowProgrammingWorks) Community Partners
5
star
73

namespace

High stable namespace registry of algorithms, tools, data structures, modules, components, etc.
JavaScript
5
star
74

Infrastructure

Metarhia Common Infrastructure 📦
5
star
75

ExampleWebSite

Example Web Site for metacms
JavaScript
5
star
76

metacode

Development Environment for Metarhia Stack
4
star
77

highcode

High-code is like low-code and no-code, but with higher abstraction 🧑‍💻
JavaScript
4
star
78

prettier-config

Prettier config for Metarhia projects
4
star
79

thread-balancer

Thread load balancer
3
star
80

StopList

Community Technology Stop-list
3
star
81

.github

The first technology stack for Node.js scaled with threads
1
star