await-the
v4.4.0
Published
A utility module which provides straight-forward, powerful functions for working with async/await in JavaScript.
Downloads
5,149
Readme
Await The Promise
A utility which provides straight-forward, powerful functions for working with async/await in JavaScript.
Installation
You can install into your Node.js project as a dependency with:
npm install await-the
API Reference
Modules
Limiter
Given a collection and a task, return resolved values of the task being ran per value via emitted events.
| Param | Type | Description | | --- | --- | --- | | collection | Array | Object | collection of data to be iterated over | | task | function | The async function to be run on each value in the collection. | | options | Object | Optional overrides. | | options.limit | Number | Optional limit to # of tasks to run in parallel. |
Example
const the = require('await-the');
const functions = [
async () => {
await the.wait(1000);
return 'waiter';
},
() => {
return 'check please';
}
];
const limiter = new the.Limiter(functions, { limit: 1 });
limiter.on('iteration', ({ key, resultValue }) => {
// resultValue - value of function ran
// key - key of collection the function was run for
});
limiter.on('done', () => {
return done();
});
limiter.on('error', ({error}) => {
// error - error when running functions
});
// begin iteration
limiter.start();
all ⇒ Array
Given a collection of functions, promises, or basic types 'run' them all at a specified limit
Returns: Array - array of the resolved promises
| Param | Type | Description | | --- | --- | --- | | collection | Array | Object | Array or object of items to run the asynchronous task with. | | options | Object | Optional overrides. | | options.limit | Number | Optional limit to # of tasks to run in parallel. |
Example
const the = require('await-the');
await the.all(
[
new Promise(resolve => resolve('hello')),
'world',
() => 'how are you?'
],
{ limit: 2 }
);
any ⇒ Boolean
Given a collection and a task return true if any promise resolves
Returns: Boolean - true if a promise resolves otherwise throws an error
| Param | Type | Description | | --- | --- | --- | | collection | Array | Object | Array or object of items to run the asynchronous task over. | | task | function | The async function to be run on each value in the collection. |
Example
const the = require('await-the')
const collection = ['item1', 'item2', 'item3'];
const task = async (value, index) => {
if (index === 1) {
return await new Promise(resolve => resolve());
} else {
throw new Error('test error');
}
};
const result = await the.any(collection, task);
// result is true
callback
Utility for making optional callbacks easier. If an error param exists, it will throw an error for promises or return the error to a callback.
| Param | Type | Description | | --- | --- | --- | | callback | function | If present will invoke the callback with the err and result; otherwise, return or throw. | | err | Object | String | Number | Boolean | Error to throw or return to the caller. | | result | * | The thrown error or the result to return to the calling function. |
Example
const the = require('await-the');
const myFunc = async (args, callback) => {
try {
const result = await somePromise();
return the.callback(callback, null, result);
} catch (e) {
return the.callback(callback, e);
}
};
// call as a promise
await myFunc(args);
// or as a callback
myFunc(args, (err, result) => {});
deadline ⇒ Promise
Run the passed function, if it takes longer than the configured time throw an error, otherwise return the results of the original function execution.
On timeout, this does NOT abort the execution of the function!
Returns: Promise - A promise
| Param | Type | Description | | --- | --- | --- | | task | function | The async function to be run. | | time | Number | The time in milliseconds this function should be allowed to run. | | error | String | Optionally, a custom error message to use. |
Example
const the = require('await-the');
await the.deadline(someAsyncFunction, 5000);
// will call `someAsyncFunction` and let it execute for 5000 ms, rejecting if it exceeds that time.
each
Given a collection, run the given asynchronous task in parallel for each value of the collection.
| Param | Type | Description | | --- | --- | --- | | collection | Array | Object | Array or object of items to run the asynchronous task with. | | task | function | The async function to be run on each value in the collection. | | options | Object | Optional overrides. | | options.limit | Number | Optional limit to # of tasks to run in parallel. |
Example
const the = require('await-the');
await the.each([1,2,3], someAsyncFunction, { limit: 2 });
// will call `someAsyncFunction` on each value of the collection, with at most two functions
// running in parallel at a time.
every ⇒ Boolean
Given a collection and a task return true if all promises resolve. Will bail on first error
Returns: Boolean - true if all promises resolve, otherwise throws the error from the first rejected promise it encounters
| Param | Type | Default | Description | | --- | --- | --- | --- | | collection | Array | Object | | Array or object of items to run the asynchronous task over. | | task | function | | Promise to be awaited for each key, called with (value, key). | | options | Object | | Optional overrides. | | options.limit | Number | Infinity | Number of concurrently pending promises returned by mapper. |
Example
const the = require('await-the')
const collection = ['item1', 'item2', 'item3'];
const task = async (value, index) => {
return await new Promise(resolve => resolve());
};
const result = await the.every(collection, task);
// result is true
map ⇒ Array
Given a collection run a map over it
Returns: Array - An array containing the results for each index
| Param | Type | Default | Description | | --- | --- | --- | --- | | collection | Array | | to iterate over | | task | Promise | | Promise to be await for each key, called with (value, key). | | options | Object | | Optional overrides. | | options.limit | Number | Infinity | Number of concurrently pending promises returned by mapper. |
Example
const the = require('await-the');
const result = await the.map(['item1'], async (value, key) => {
return somePromise(value);
});
// result is now an object with [<resolved promise>]
mapValues ⇒ Object
Given an object of key-value pairs, run the given asynchronous task in parallel for each pair.
Returns: Object - An object containing the results for each key.
| Param | Type | Default | Description | | --- | --- | --- | --- | | collection | Object | | Key-value pair to be iterated over. | | task | Promise | | Promise to be await for each key, called with (value, key). | | options | Object | | Optional overrides. | | options.limit | Number | Infinity | Number of concurrently pending promises returned by mapper. |
Example
const the = require('await-the');
const result = await the.mapValues({key1: 'value1'}, async (value, key) => {
return somePromise(value);
});
// result is now an object with {key1: <resolved promise> }
multiResult ⇒ Array
Given a function that expects a callback as its last argument, await a promisified version of that function and return the arguments sent to the callback as an array.
Returns: Array - The arguments sent to the callback, including the error.
| Param | Type | Description | | --- | --- | --- | | fn | function | Array | The async function to promisify and call, or an array of [class, method name]. | | ...args | * | Variadic arguments to send to the function, excluding the callback. Note that all parameters of the function besides the callback must have values supplied, even if they're optional. |
Example
const the = require('await-the');
const asyncSum = (x, y, callback) => callback(null, x + y, x * y);
const [err, sum, product] = await the.multiResult(asyncSum, 1, 2);
// will assign null to `err`, 3 to `sum` and 2 to `product`.
await the.multiResult([someObj, 'someFnName'], 1, 2);
// equivalent of `await the.multiResult(someObj.someFnName.bind(someObj), 1, 2)`
const someFnWithOptionalArgs = (x, y = 1, opts = {}, callback) => callback(null, x + y);
await the.multiResult(someFnWithOptionalArgs, 2, 1, {});
// if the function has optional params before the callback, values must be supplied for all
result ⇒ *
Given a function that expects a callback as its last argument, await a promisified version of that function and return the result.
Returns: * - The thrown error or the result.
| Param | Type | Description | | --- | --- | --- | | fn | function | Array | The async function to promisify and call, or an array of [class, method name]. | | ...args | * | Variadic arguments to send to the function, excluding the callback. Note that all parameters of the function besides the callback must have values supplied, even if they're optional. |
Example
const the = require('await-the');
const asyncSum = (x, y, callback) => callback(null, x + y);
const sum = await the.result(asyncSum, 1, 2);
// will assign 3 to `sum`
await the.result([someObj, 'someFnName'], 1, 2);
// equivalent of `await the.result(someObj.someFnName.bind(someObj), 1, 2)`
const someFnWithOptionalArgs = (x, y = 1, opts = {}, callback) => callback(null, x + y);
await the.result(someFnWithOptionalArgs, 2, 1, {});
// if the function has optional params before the callback, values must be supplied for all
retry ⇒ *
Retry promise a given number of times at an interval.
Returns: * - The last thrown error or the result.
| Param | Type | Description | | --- | --- | --- | | promise | Promise | The promise to be resolved (or rejected) on the retry cadence. | | options | Object | Optional overrides. | | options.maxTries | Number | Maximum number of times to retry to promise. | | options.interval | Number | function | Time to wait in ms between promise executions. | | options.errorFilter | Any | function | Promise | if supplied only retry if Any === error.message or function returns true |
Example
const the = require('await-the');
await the.retry(myPromise, { maxTries: 10, interval: 100 });
await the.retry(myPromise, { maxTries: 10, interval: numTriesSoFar => (numTriesSoFar * 100) });
await the.retry(myPromise, { maxTries: 10, interval: errorFilter: 'My Expected Error' });
await the.retry(myPromise, { maxTries: 10, interval: errorFilter: err => err.message === 'My Expected Error' });
wait ⇒ Promise
Promise based wait utility.
| Param | Type | Description | | --- | --- | --- | | time | Number | Time in ms to wait before returning a resolved promise. |
Example
const the = require('await-the');
// wait for 1 second before returning
await the.wait(1000);
while ⇒ *
Given a condition and function, continuously call the promisified version of that function sequentially and return the result once the exiting condition is met.
The condition
can access either the parent scoped variables or the results of fn
which are passed in
as the only parameter.
Returns: * - The thrown error or the result.
| Param | Type | Description | | --- | --- | --- | | condition | function | The condition to continue looping. | | fn | function | Array | The function to be resolved (or rejected) every loop. | | ...args | * | Variadic arguments to send to the function. |
Example
const the = require('await-the');
let sum = 0;
const condition = previousResult => sum < 10;
const asyncFn = x => {
sum += x;
return sum * 10;
}
const result = await the.while(condition, asyncFn, 2);
// will loop while sum < 10, then return the final function result
// sum === 10
// result === 100
whileMax ⇒ *
Given a condition, maximum amount of loop iterations to do, and function, continuously call the promisified version of that function sequentially and return the result once the exiting condition is met or the loop count has been exhausted.
The condition
can access either the parent scoped variables or the results of fn
which are passed in
as the only parameter.
Returns: * - The thrown error or the result.
| Param | Type | Description | | --- | --- | --- | | condition | function | The condition to continue looping. | | maxIterations | Number | The maximum amount of loop iterations to be done. | | fn | function | Array | The function to be resolved (or rejected) every loop. | | ...args | * | Variadic arguments to send to the function. |
Example
const the = require('await-the');
let sum = 0;
const max = 2;
const condition = previousResult => sum < 10;
const asyncFn = x => {
sum += x;
return sum * 10;
}
const result = await the.whileMax(condition, max, asyncFn, 2);
// is cut off by hitting the max loops possible
// sum === 4
// result === 40
NPM Options
The different package NPM options.
Test
Runs the linter and all Mocha tests in the test
directory.
npm test
Lint
Analyse code for potential errors and styling issues.
npm run lint
Format
Fix issues found during linting.
npm run format
Build documentation
Updates this README with the API Reference.
npm run docs