async-coalesce
TypeScript icon, indicating that this package has built-in type declarations

1.0.3 • Public • Published

async-coalesce NPM version js-standard-style

coalesce

async coalesce(resolversany[], errorIfUndefined?: string)Promise<any>;
async coalesce(resolversany[], paramsany[], errorIfUndefined?: string)Promise<any>;

This function is intended for resolving a value potentially defined in higher scopes. Typical use case would be for methods accepting a configuration object whose properties could also be defined in the class constructor or some other greater scope like below:

const name = localVar | classVar | globalVar | 'default';

However, this function also handles resolving async functions which traditionally would be done like below:

let result1: string;
let result2: number;
try {
    result1 = (await localMethod(localVar)) | (await classMethod(localVar)) | 'default';
    result2 = (await localMethod(localVar)) | (await classMethod(localVar)) | (await otherClassMethod(localVar));
} catch (err) {
    throw `Failed to coalesce (${err})`;
}
if (typeof result2 === 'undefined' || result2 === null) throw 'result2 is not defined';

This approach works, but can get quite verbose. This same line using async-coalesce is shown below

const result1 = await coalesce([localMethod, classMethod, 'default'], [localVar]);
const result2 = await coalesce([localMethod, classMethod, otherClassMethod], [localVar], 'result2 is not defined');

We are not wrapping this in a try block because the coalesce function will throw the 'Failed to coalesce' exception with the reason if any of the functions error. Some use cases may still require catching the error.

If the second parameter is an array of values, they will be applied as parameters to each function that is a resolver. If each function will accept different parameters, just set the resolver value as the result of the function, and do not include the params array. If the second parameter is a string, this will be the error text.

const result1 = await coalesce([localMethod(var1, var2), classMethod(var1, var3)], 'Say what!?');

Note

This function will still error if it is passed a parameter that is a property of an undefined value. For example:

const obj1 = { 
    prop: 'hello, world'
}
 
const obj2;
 
const result1 = await coalesce([obj1.prop, obj2.prop, 'default'], [localVar]);
 

This will throw a "Cannot access '.prop' on undefined" error. It is recommended that referenced objects be instantiated with a default value.

const obj2 = {};

coalesceSync

coalesceSync(resolversany[], paramsany[] = [], errorIfUndefined?: string) => any

This function is also available for use in a constructor, or some other area were async/await does not work. It does not support async resolvers.

License

MIT

Readme

Keywords

Package Sidebar

Install

npm i async-coalesce

Weekly Downloads

0

Version

1.0.3

License

MIT

Unpacked Size

11.6 kB

Total Files

6

Last publish

Collaborators

  • marqit8