• Stars
    star
    133
  • Rank 272,600 (Top 6 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 10 years ago
  • Updated over 1 year ago

Reviews

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

Repository Details

Compose your async functions with elegance.

bach

NPM version Downloads Build Status Coveralls Status

Compose your async functions with elegance.

Usage

With bach, it is very easy to compose async functions to run in series or parallel.

var bach = require('bach');

function fn1(cb) {
  cb(null, 1);
}

function fn2(cb) {
  cb(null, 2);
}

function fn3(cb) {
  cb(null, 3);
}

var seriesFn = bach.series(fn1, fn2, fn3);
// fn1, fn2, and fn3 will be run in series
seriesFn(function (err, res) {
  if (err) {
    // in this example, err is undefined
    // handle error
  }
  // handle results
  // in this example, res is [1, 2, 3]
});

var parallelFn = bach.parallel(fn1, fn2, fn3);
// fn1, fn2, and fn3 will be run in parallel
parallelFn(function (err, res) {
  if (err) {
    // in this example, err is undefined
    // handle error
  }
  // handle results
  // in this example, res is [1, 2, 3]
});

Since the composer functions return a function, you can combine them.

var combinedFn = bach.series(fn1, bach.parallel(fn2, fn3));
// fn1 will be executed before fn2 and fn3 are run in parallel
combinedFn(function (err, res) {
  if (err) {
    // in this example, err is undefined
    // handle error
  }
  // handle results
  // in this example, res is [1, [2, 3]]
});

Functions are called with async-done, so you can return a stream, promise, observable or child process. See async-done completion and error resolution for more detail.

// streams
var fs = require('fs');

function streamFn1() {
  return fs
    .createReadStream('./example')
    .pipe(fs.createWriteStream('./example'));
}

function streamFn2() {
  return fs
    .createReadStream('./example')
    .pipe(fs.createWriteStream('./example'));
}

var parallelStreams = bach.parallel(streamFn1, streamFn2);
parallelStreams(function (err) {
  if (err) {
    // in this example, err is undefined
    // handle error
  }
  // all streams have emitted an 'end' or 'close' event
});
// promises
function promiseFn1() {
  return Promise.resolve(1);
}

function promiseFn2() {
  return Promise.resolve(2);
}

var parallelPromises = bach.parallel(promiseFn1, promiseFn2);
parallelPromises(function (err, res) {
  if (err) {
    // in this example, err is undefined
    // handle error
  }
  // handle results
  // in this example, res is [1, 2]
});

All errors are caught in a domain and passed to the final callback as the first argument.

function success(cb) {
  setTimeout(function () {
    cb(null, 1);
  }, 500);
}

function error() {
  throw new Error('Thrown Error');
}

var errorThrownFn = bach.parallel(error, success);
errorThrownFn(function (err, res) {
  if (err) {
    // handle error
    // in this example, err is an error caught by the domain
  }
  // handle results
  // in this example, res is [undefined]
});

When an error happens in a parallel composition, the callback will be called as soon as the error happens. If you want to continue on error and wait until all functions have finished before calling the callback, use settleSeries or settleParallel.

function success(cb) {
  setTimeout(function () {
    cb(null, 1);
  }, 500);
}

function error(cb) {
  cb(new Error('Async Error'));
}

var parallelSettlingFn = bach.settleParallel(success, error);
parallelSettlingFn(function (err, res) {
  // all functions have finished executing
  if (err) {
    // handle error
    // in this example, err is an error passed to the callback
  }
  // handle results
  // in this example, res is [1]
});

API

series(fns..., [options])

Takes a variable amount of functions (fns) to be called in series when the returned function is called. Optionally, takes an options object as the last argument.

Returns an invoker(cb) function to be called to start the serial execution. The invoker function takes a callback (cb) with the function(error, results) signature.

If all functions complete successfully, the callback function will be called with all results as the second argument.

If an error occurs, execution will stop and the error will be passed to the callback function as the first parameter. The error parameter will always be a single error.

parallel(fns..., [options])

Takes a variable amount of functions (fns) to be called in parallel when the returned function is called. Optionally, takes an options object as the last argument.

Returns an invoker(cb) function to be called to start the parallel execution. The invoker function takes a callback (cb) with the function(error, results) signature.

If all functions complete successfully, the callback function will be called with all results as the second argument.

If an error occurs, the callback function will be called with the error as the first parameter. Any async functions that have not completed, will still complete, but their results will not be available. The error parameter will always be a single error.

settleSeries(fns..., [options])

Takes a variable amount of functions (fns) to be called in series when the returned function is called. Optionally, takes an options object as the last argument.

Returns an invoker(cb) function to be called to start the serial execution. The invoker function takes a callback (cb) with the function(error, results) signature.

All functions will always be called and the callback will receive all settled errors and results. If any errors occur, the error parameter will be an array of errors.

settleParallel(fns..., [options])

Takes a variable amount of functions (fns) to be called in parallel when the returned function is called. Optionally, takes an options object as the last argument.

Returns an invoker(cb) function to be called to start the parallel execution. The invoker function takes a callback (cb) with the function(error, results) signature.

All functions will always be called and the callback will receive all settled errors and results. If any errors occur, the error parameter will be an array of errors.

options

The options object is primarily used for specifying functions that give insight into the lifecycle of each function call. The possible extension points are create, before, after and error. If an extension point is not specified, it defaults to a no-op function.

The options object for parallel and settleParallel also allows specifying concurrency in which to run your functions. By default, your functions will run at maximum concurrency.

options.concurrency

Limits the amount of functions allowed to run at a given time.

options.create(fn, index)

Called at the very beginning of each function call with the function (fn) being executed and the index from the array/arguments. If create returns a value (storage), it is passed to the before, after and error extension points.

If a value is not returned, an empty object is used as storage for each other extension point.

This is useful for tracking information across an iteration.

options.before(storage)

Called immediately before each function call with the storage value returned from the create extension point.

options.after(result, storage)

Called immediately after each function call with the result of the function and the storage value returned from the create extension point.

options.error(error, storage)

Called immediately after a failed function call with the error of the function and the storage value returned from the create extension point.

License

MIT

More Repositories

1

gulp

A toolkit to automate & enhance your workflow
JavaScript
32,962
star
2

vinyl

Virtual file format.
JavaScript
1,272
star
3

vinyl-fs

Vinyl adapter for the file system.
JavaScript
966
star
4

liftoff

Launch your command line tool with ease.
JavaScript
840
star
5

gulp-util

[deprecated] - See https://medium.com/gulpjs/gulp-util-ca3b1f9f9ac5
JavaScript
829
star
6

gulp-cli

Command Line Interface for gulp.
JavaScript
397
star
7

plugins

[Unused] Very old plugin search website
JavaScript
280
star
8

interpret

A dictionary of file extensions and associated module loaders.
JavaScript
259
star
9

undertaker

Task registry that allows composition through series/parallel methods.
JavaScript
198
star
10

glob-stream

Readable streamx interface over anymatch.
JavaScript
178
star
11

fancy-log

Log things, prefixed with a timestamp.
JavaScript
120
star
12

findup-sync

Find the first file matching a given pattern in the current directory or the nearest ancestor directory.
JavaScript
98
star
13

glob-watcher

Watch globs and execute a function upon change, with intelligent defaults for debouncing and queueing.
JavaScript
80
star
14

glob-parent

Extract the non-magic parent path from a glob string.
JavaScript
79
star
15

async-done

Allows libraries to handle various caller provided asynchronous functions uniformly. Maps promises, observables, child processes and streams, and callbacks to callback style.
JavaScript
69
star
16

gulplog

Logger for gulp and gulp plugins.
JavaScript
56
star
17

v8flags

Get available v8 and Node.js flags.
JavaScript
56
star
18

rechoir

Prepare a node environment to require files with different extensions.
JavaScript
48
star
19

replace-ext

Replaces a file extension with another one.
JavaScript
46
star
20

gulpjs.github.io

The gulp website
JavaScript
45
star
21

ordered-read-streams

Combines array of streams into one Readable stream in strict order.
JavaScript
28
star
22

now-and-later

Map over an array or object of values in parallel or series, passing each through the async iterator, with optional lifecycle hooks.
JavaScript
24
star
23

hacker

Hack on your project easily. A liftoff proof-of-concept.
JavaScript
24
star
24

flagged-respawn

A tool for respawning node binaries when special flags are present.
JavaScript
21
star
25

artwork

Artwork for the gulp project
21
star
26

empty-dir

Check if a directory is empty.
JavaScript
20
star
27

sparkles

Namespaced global event emitter.
JavaScript
20
star
28

acceptance

Acceptance test suite for plugins
19
star
29

undertaker-forward-reference

Undertaker custom registry supporting forward referenced tasks.
JavaScript
19
star
30

plugin-error

Error handling for vinyl plugins. Just an abstraction of what's in gulp-util with minor reformatting.
JavaScript
19
star
31

glogg

Global logging utility.
JavaScript
18
star
32

lead

Sink your streams.
JavaScript
17
star
33

undertaker-registry

Default registry in gulp 4.
JavaScript
17
star
34

vinyl-sourcemap

Add/write sourcemaps to/from Vinyl files.
JavaScript
15
star
35

last-run

Capture and retrieve the last time a function was run
JavaScript
14
star
36

path-dirname

Node.js path.dirname() ponyfill
JavaScript
13
star
37

fined

Find a file given a declaration of locations.
JavaScript
12
star
38

async-settle

Settle an async function. It will always complete successfully with an object of the resulting state.
JavaScript
11
star
39

value-or-function

Normalize a value or function, applying extra args to the function
JavaScript
11
star
40

copy-props

Copy properties deeply between two objects
JavaScript
10
star
41

to-through

Wrap a Readable stream in a Transform stream.
JavaScript
10
star
42

semver-greatest-satisfied-range

Find the greatest satisfied semver range from an array of ranges.
JavaScript
9
star
43

mute-stdout

Mute and unmute stdout
JavaScript
9
star
44

resolve-options

Resolve an options object based on configuration.
JavaScript
9
star
45

has-gulplog

Check if gulplog is available before attempting to use it
JavaScript
9
star
46

clone-buffer

Easier Buffer cloning in node.
JavaScript
9
star
47

eslint-config-gulp

Sharable eslint config for gulp projects
JavaScript
8
star
48

async-once

Guarantee a node-style async function is only executed once.
JavaScript
8
star
49

fs-mkdirp-stream

Ensure directories exist before writing to them.
JavaScript
8
star
50

undertaker-common-tasks

Proof-of-concept custom registry that pre-defines tasks.
JavaScript
7
star
51

remove-bom-stream

Remove a UTF8 BOM at the start of the stream.
JavaScript
7
star
52

registry

[Unused] NPM on ElasticSearch
JavaScript
5
star
53

better-stats

A replacement for node's fs.Stats with more utility
JavaScript
5
star
54

theming-log

Creates a logger with theme for text decoration.
JavaScript
4
star
55

undertaker-task-metadata

Proof-of-concept custom registry that attaches metadata to each task.
JavaScript
4
star
56

replace-homedir

Replace user home in a string with another string. Useful for tildifying a path.
JavaScript
4
star
57

evented-require

Require modules and receive events.
JavaScript
3
star
58

each-props

Process object properties deeply.
JavaScript
3
star
59

vinyl-contents

Utility to read the contents of a vinyl file.
JavaScript
3
star
60

.boilerplate

The boilerplate template for gulp packages.
3
star
61

update-template

Updates a gulpjs repository to match our current scaffold.
JavaScript
3
star
62

vinyl-prepare

[deprecated] This module's API was never satisfactory and isn't used in gulp - please don't use.
JavaScript
3
star
63

parse-node-version

Turn node's process.version into something useful.
JavaScript
2
star
64

default-resolution

Get the default resolution time based on the current node version, optionally overridable
JavaScript
2
star
65

.github

GitHub template files for the gulpjs organization.
2
star
66

jscs-preset-gulp

Sharable jscs config for gulp projects
2
star
67

conventional-changelog-gulp

conventional-changelog gulp preset
JavaScript
1
star
68

emit-mapper

Re-emit events while mapping them to new names.
JavaScript
1
star