promise-flow
Utility module for functions that return promises
Example
import * as pf from 'promise-flow';
pf.allObject({
key1: Promise.resolve('value from a promise'),
key2: 'non-promise value'
}).then(function(result) {
});
API
allObject(object)
allObject<T>(object: { [key: string]: Promise<T> | T }): Promise<{ [key: string]: T }>
Returns a promise that resolves with a copy of the input object when all values have resolved.
promise_flow.allObject({
key1: Promise.resolve('value from a promise'),
key2: 'non-promise value'
}).then(function(result) {
});
series(factories)
series<T>(factories: Array<() => Promise<T> | T): Promise<Array<T>>
Takes an array of functions that will be executed in series. Each one will wait until the previous function is done.
If one of the functions returns a rejected promise or throws an error then the resulting promise will reject with that error.
promise_flow.series([
() => Promise.resolve('value from a promise'),
() => 'non-promise value'
]).then(function(result) {
});
parallel(factories)
parallel<T>(factories: Array<() => Promise<T> | T): Promise<Array<T>>
Same as series
but will run all functions in parallel.
map(array, closure)
map<T, U>(array: Array<T>, closure: (value: T, index: number) => Promise<U> | U): Promise<Array<U>>
Map the items in the array with a function that may return a promise.
mapSeries(array, closure)
map<T, U>(array: Array<T>, closure: (value: T, index: number) => Promise<U> | U): Promise<Array<U>>
Same as map
but will run all functions in series.
filter(array, closure)
filter<T>(array: Array<T>, closure: (value: T, index: number) => Promise<boolean> | boolean): Promise<Array<T>>
Filter the array using a function that may return a promise.
To keep a value in the array, return a promise that resolves with a truthy value (or return the value directly).
filterSeries(array, closure)
filterSeries<T>(array: Array<T>, closure: (value: T, index: number) => Promise<boolean> | boolean): Promise<Array<T>>
Same as filter
but will run all functions in series.
entangledCallback(optional_value_resolver)
entangledCallback<T>(optional_value_resolver?: (...values: Array<any>) => T): [Promise<T>, (err: ?Error, ...values: Array<any>) => void]
Returns a tuple where the first item is a promise and the second item is a node-style callback function. The two are connected so that when the callback is invoked, the promise will be resolved.
An optional function can be provided to reduce arguments passed to the callback to a single value.
import { readFile } from 'fs';
function myReadFile(filename, options) {
const [promise, callback] = promise_flow.entangledCallback();
readFile(filename, options, callback);
return promise;
}
myReadFile('./file.txt').then(handleFileData, handleReadError);
const [promise, callback] = promise_flow.entangledCallback();
const [promise, callback] = promise_flow.entangledCallback(Array.of);