4.4.0 • Published 8 months ago

await-the v4.4.0

Weekly downloads
10,012
License
MIT
Repository
github
Last release
8 months ago

Await The Promise

Build
Status code style:
prettier

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.

ParamTypeDescription
collectionArray | Objectcollection of data to be iterated over
taskfunctionThe async function to be run on each value in the collection.
optionsObjectOptional overrides.
options.limitNumberOptional 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

ParamTypeDescription
collectionArray | ObjectArray or object of items to run the asynchronous task with.
optionsObjectOptional overrides.
options.limitNumberOptional 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

ParamTypeDescription
collectionArray | ObjectArray or object of items to run the asynchronous task over.
taskfunctionThe 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.

ParamTypeDescription
callbackfunctionIf present will invoke the callback with the err and result; otherwise, return or throw.
errObject | String | Number | BooleanError 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

ParamTypeDescription
taskfunctionThe async function to be run.
timeNumberThe time in milliseconds this function should be allowed to run.
errorStringOptionally, 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.

ParamTypeDescription
collectionArray | ObjectArray or object of items to run the asynchronous task with.
taskfunctionThe async function to be run on each value in the collection.
optionsObjectOptional overrides.
options.limitNumberOptional 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

ParamTypeDefaultDescription
collectionArray | ObjectArray or object of items to run the asynchronous task over.
taskfunctionPromise to be awaited for each key, called with (value, key).
optionsObjectOptional overrides.
options.limitNumberInfinityNumber 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

ParamTypeDefaultDescription
collectionArrayto iterate over
taskPromisePromise to be await for each key, called with (value, key).
optionsObjectOptional overrides.
options.limitNumberInfinityNumber 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.

ParamTypeDefaultDescription
collectionObjectKey-value pair to be iterated over.
taskPromisePromise to be await for each key, called with (value, key).
optionsObjectOptional overrides.
options.limitNumberInfinityNumber 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.

ParamTypeDescription
fnfunction | ArrayThe 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.

ParamTypeDescription
fnfunction | ArrayThe 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.

ParamTypeDescription
promisePromiseThe promise to be resolved (or rejected) on the retry cadence.
optionsObjectOptional overrides.
options.maxTriesNumberMaximum number of times to retry to promise.
options.intervalNumber | functionTime to wait in ms between promise executions.
options.errorFilterAny | function | Promiseif 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.

ParamTypeDescription
timeNumberTime 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.

ParamTypeDescription
conditionfunctionThe condition to continue looping.
fnfunction | ArrayThe 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.

ParamTypeDescription
conditionfunctionThe condition to continue looping.
maxIterationsNumberThe maximum amount of loop iterations to be done.
fnfunction | ArrayThe 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
4.4.0

8 months ago

4.3.4

8 months ago

4.3.3

2 years ago

4.3.2

3 years ago

4.3.1

4 years ago

4.3.0

4 years ago

4.2.1

4 years ago

4.2.0

4 years ago

4.1.0

4 years ago

4.0.0

5 years ago

3.2.0

5 years ago

3.1.5

5 years ago

3.1.4

5 years ago

3.1.3

5 years ago

3.1.2

5 years ago

3.1.1

5 years ago

3.1.0

5 years ago

3.0.1

5 years ago

3.0.0

5 years ago

2.0.1

6 years ago

2.0.0

6 years ago

1.5.4

6 years ago

1.5.3

6 years ago

1.5.2

6 years ago

1.5.0

6 years ago