BloodhoundPromise

BloodhoundPromise

new BloodhoundPromise(executor)

Source:

Promise with extra features.

Examples
new BloodhoundPromise((resolve, reject) => {
  setTimeout(() => {
    resolve(result); // or:
    reject(new Error('something bad happened'));
  });
});
import asBloodhound from 'bloodhound-promises';

const BloodhoundPromise = asBloodhound(Promise);
const stop = log.startTiming('async operation');

BloodhoundPromise.delay(10)
  .then(() => doSomethingAsync())
  .timeout(15000, new Error('async operation timed out'))
  .tap((result) => log.event('received value:', result))
  .catch('TypeError', 'EvalError', (e) => log.error(e))
  .done((result) => stop({ result }));
Parameters:
Name Type Description
executor Executor

Invoked with resolve and reject functions to settle the promise.

Members

(static) config :Config

Source:

Provides methods to configure BloodhoundPromise.

Type:
Examples
BloodhoundPromise.config.setErrorHandler((error) => {
  console.log('unhandled promise rejection!', error);
});
BloodhoundPromise.config.setAsyncNotifier(() => {
  console.log('a promise callback was just invoked');
});

Methods

(static) all(promises) → {BloodhoundPromise.<(array|object)>}

Source:

Resolves the returned promise only if all the specified promises resolve.

Examples
BloodhoundPromise.all({
  a: someAsyncOperation(),
  b: BloodhoundPromise.delay(1000, 'default'),
  c: BloodhoundPromise.reject(new Error('oops'))
}).catch(console.log); // <Error: oops>
BloodhoundPromise.all([
  someAsyncOperation(),
  BloodhoundPromise.delay(1000, 'default')
]).then(console.log); // [ …, 'default' ]
BloodhoundPromise.all([
  'abc',
  new Error(123)
]).catch(console.error); // <Error: 123>
Parameters:
Name Type Description
promises Iterable | Map | object

The promises to wait to resolve.

Returns:

A new promise resolved with an array of resolved values if an iterable was provided or an object if an object or Map was provided. The object's keys will be the keys in the original object and the values will be the resolved values. If any of the promises rejects, the rejection handler will be invoked with the first rejection reason.

Type
BloodhoundPromise.<(array|object)>

(static) any(promises) → {BloodhoundPromise.<(array|object)>}

Source:

Resolves the returned promise if any the specified promises resolve.

Examples
BloodhoundPromise.any({
  a: someAsyncOperation(),
  b: BloodhoundPromise.delay(1000, 'default'),
  c: BloodhoundPromise.reject(new Error())
}).then(console.log); // { b: 'default' }
BloodhoundPromise.any([
  someAsyncOperation(),
  BloodhoundPromise.delay(1000, 'default'),
  BloodhoundPromise.reject(new Error())
]).then(console.log); // [ 'default' ]
BloodhoundPromise.any([
  new Error(123),
  BloodhoundPromise.reject('abc')
]).catch(console.error); // [<Error: 123>, 'abc']
Parameters:
Name Type Description
promises Iterable | Map | object

The promises to wait for one to resolve.

Returns:

A new promise resolved with an array containing the first resolved value if an iterable was provided or an object if an object or Map was provided. The object's only key will be the key of the first resolved promise in the original object and the value will be that first resolved value. If all of the promises reject, the rejection handler will be invoked with an array of all the rejection reasons.

Type
BloodhoundPromise.<(array|object)>

(static) apply(fn, args) → {BloodhoundPromise}

Source:

Invokes the specified function with the given arguments. The promise will be rejected if an Error is thrown while invoking the function.

Example
function divide(arg1, arg2) {
  return arg1 / arg2;
}
BloodhoundPromise.apply(divide, [50, 10]).then(…);
BloodhoundPromise.apply(divide, [50, 0]).catch(…); // division by zero
Parameters:
Name Type Description
fn function

The function to invoke.

args array

The arguments to pass to the function.

Returns:

A new promise instance.

Type
BloodhoundPromise

(static) call(fn, …args) → {BloodhoundPromise}

Source:

Invokes the specified function with the given arguments. The promise will be rejected if an error is thrown while invoking the function.

Example
function divide(arg1, arg2) {
  return arg1 / arg2;
}
BloodhoundPromise.call(divide, 50, 10).then(…);
BloodhoundPromise.call(divide, 50, 0).catch(…); // division by zero
Parameters:
Name Type Attributes Description
fn function

The function to invoke.

args Array.<any> <repeatable>

The arguments to pass to the function.

Returns:

A new promise instance.

Type
BloodhoundPromise

(static) cast(value) → {BloodhoundPromise}

Source:

Converts the specified value to a BloodhoundPromise.

Example
BloodhoundPromise.cast(123).then(…);
BloodhoundPromise.cast(anotherPromise).then(…, …);
Parameters:
Name Type Description
value any

The value to cast as a BloodhoundPromise. If a Promise-like object is provided, the returned promise will be settled when the provided promise settles. If an Error is provided, the returned promise will be rejected with that reason.

Returns:

A new promise instance.

Type
BloodhoundPromise

(static) defer() → {Defer}

Source:
Deprecated:
  • The Defer pattern breaks encapsulation and divides responsibility, and so should be avoided. Instead, use the normal Promise constructor callback pattern.

Creates an object that references a new BloodhoundPromise as well as the methods to use to resolve or reject that promise later.

Example
// WARNING: deprecated
const defer = BloodhoundPromise.defer();
setTimeout(() => defer.resolve('abc'), 10);
defer.promise.then(…);
Returns:

A new Defer instance.

Type
Defer

(static) delay(ms, result) → {BloodhoundPromise}

Source:

Settles the returned promise with the given value after the specified time. If an Error is provided, the returned promise will be rejected. If a Promise is provided, the returned promise will wait for the given promise to settled and match its state.

Example
BloodhoundPromise.delay(1000, 'async value').then(…);
BloodhoundPromise.delay(1000, new Error('rejected')).catch(…);
Parameters:
Name Type Description
ms number

The number of milliseconds to delay before settling the promise.

result any

The value to settle the promise with.

Returns:

A new promise instance.

Type
BloodhoundPromise

(static) isPromise(object) → {boolean}

Source:

Determines if the specified object can be treated like a Promise.

Example
BloodhoundPromise.isPromise(123); // false
BloodhoundPromise.isPromise(Promise.resolve()); // true
BloodhoundPromise.isPromise(BloodhoundPromise.cast(123)); // true
Parameters:
Name Type Description
object any

The value to check.

Returns:

True if the value is a Promise-like object; otherwise, false.

Type
boolean

(static) race(promises) → {BloodhoundPromise}

Source:

Settles the returned promise with the first of the given promises to resolve or reject.

Example
BloodhoundPromise.race([
    someAsyncOperation(),
    BloodhoundPromise.delay(10000, new Error('operation timed out'))
]).then(…, …);
Parameters:
Name Type Description
promises Iterable

The collection of promises to race.

Returns:

A new promise instance.

Type
BloodhoundPromise

(static) reject(error) → {BloodhoundPromise}

Source:

Creates a new BloodhoundPromise rejected with the given reason. Best practice is to always reject your Promises with an Error instance, not a string or undefined.

Example
BloodhoundPromise.reject(new Error('bad data'));
Parameters:
Name Type Description
error any

The reason the promise is rejected.

Returns:

A new promise instance rejected with the given reason.

Type
BloodhoundPromise

(static) resolve(value) → {BloodhoundPromise}

Source:

Creates a new BloodhoundPromise resolved with the given value. If an Error instance is provided, the returned promise will be rejected.

Example
BloodhoundPromise.resolve(123);
BloodhoundPromise.resolve(someOtherPromise).then(…);
BloodhoundPromise.resolve(new Error('rejection reason')).catch(…);
Parameters:
Name Type Description
value any

The value to resolve a new promise with.

Returns:

A new promise instance resolved with the given value.

Type
BloodhoundPromise

(static) settle(promises) → {BloodhoundPromise.<(array|object)>}

Source:

Resolves the returned promise when all the given promises settle (resolved or rejected).

Examples
BloodhoundPromise.hash({
  a: someAsyncOperation(),
  b: BloodhoundPromise.delay(1000, 'default'),
  c: BloodhoundPromise.reject(new Error())
}).then(console.log); // { a: <Promise>, b: <Promise>, c: <Promise> }
BloodhoundPromise.settle([
  someAsyncOperation(),
  BloodhoundPromise.delay(1000, 'default'),
  BloodhoundPromise.reject(new Error())
]).then(console.log); // [ <Promise>, <Promise>, <Promise> ]
Parameters:
Name Type Description
promises Iterable | Map | object

The promises to wait to settle.

Returns:

A new promise instance resolved with an array of promises if an iterable was provided.or an object if an object or Map was provided. The object's keys will be the keys in the original object and the values will be the promises. To determine the state of the Promise instance use isResolved() or isRejected(). To get the rejection reason or resolved value, use value().

Type
BloodhoundPromise.<(array|object)>

(static) some(promises, count) → {BloodhoundPromise.<(array|object)>}

Source:

Resolves the returned promise when the specified number of the given promises has resolved. Otherwise, if not enough of the promises can resolve to meet the requested minimum count, the returned promise will be rejected.

Examples
BloodhoundPromise.some({
  a: someAsyncOperation(),
  b: BloodhoundPromise.delay(1000, 'default'),
  c: BloodhoundPromise.reject(new Error())
}, 2).then(console.log); // { a: …, b: 'default' }
BloodhoundPromise.some([
  someAsyncOperation(),
  BloodhoundPromise.delay(1000, 'default'),
  BloodhoundPromise.reject(new Error())
], 2).then(console.log); // [ …, 'default' ]
Parameters:
Name Type Description
promises Iterable | Map | object

The promises to wait to resolve.

count number

The number of promises that must resolve before the returned promise is resolved.

Returns:

A new promise instance resolved with an array of settled values if an iterable was provided or an object if an object or Map was provided. The object's keys will be the keys in the original object and the values will be the settled values.

Type
BloodhoundPromise.<(array|object)>

(static) timeout(promise, ms, erroropt) → {BloodhoundPromise}

Source:

Creates a new BloodhoundPromise that will reject with the given reason if the provided promise does not settle before the given time elapses. If the provided promise settles within the time period then the returned promise will be resolve or rejected to match.

Example
BloodhoundPromise.timeout(somePromise, 10000).catch(…);
BloodhoundPromise.timeout(somePromise, 500, new Error('operation timed out'));
Parameters:
Name Type Attributes Description
promise BloodhoundPromise

The promise that should settle before the given time has elapsed.

ms number

The number of milliseconds to wait before rejecting the returned promise.

error any <optional>

The optional value to reject the promise with if the time period elapsed before the given promise settles.

Returns:

A new promise instance.

Type
BloodhoundPromise

(static) unwrap() → {function}

Source:

Returns the original Promise constructor function passed to wrapAsBloodhound.

Example
const Promise = BloodhoundPromise.unwrap();
return new Promise((resolve, reject) => { … });
Returns:

The original Promise constructor.

Type
function

catch(…typesopt, onRejectedopt) → {BloodhoundPromise}

Source:

Invokes the specified callback if the promise rejects. The callback will be passed the rejection reason. Optionally, you can specify which Error type names the rejection reason should match for the callback to be invoked. If you pass no callback function, the promise rejection will be swallowed, resolving the promise with undefined (the same behavior you would get by passing a no-op as your rejection handler).

Examples
BloodhoundPromise.call(someMethod, 'arg')
  .catch((err) => log.error('method failed', err));
// you can swallow the rejection by not passing a function (same behavior
// as passing a no-op), resolving the final promise with undefined
BloodhoundPromise.call(someMethod, 'arg')
  .catch('TypeError') // swallow TypeErrors
  .catch() // swallow all errors, same as .catch(() => {})
Parameters:
Name Type Attributes Description
types Array.<string> <optional>
<repeatable>

The error type names to match against the rejection reason in order for the callback to be invoked. If not provided, the callback will always be invoked when the promise is rejected.

onRejected function <optional>

Method to invoke when the promise rejects. If one or more Error type names has been specified, the callback will only be invoked if the rejection reason matches the given Error type name.

Returns:

A new promise.

Type
BloodhoundPromise

done(callbackopt)

Source:

Ends the promise chain. Invokes the specified callback (if provided). Also, if the promise is rejected, invokes the callback registered using BloodhoundPromise.config.setErrorHandler.

Examples
BloodhoundPromise.call(someMethod)
  .tap(logResult)
  .then(handleResult)
  .catch() // swallow
  .done();
BloodhoundPromise.call(someMethod)
  .then(handleResult)
  .done((valueOrError) => { … });
Parameters:
Name Type Attributes Description
callback function <optional>

Optional function that will be invoked with the promise's resolved value or rejection reason when the parent promise settles.

finally(callbackopt) → {BloodhoundPromise}

Source:

Invokes the specified callback when the promise settles. If the method returns a promise, we wait for that promise to settle. Only if it rejects will this promise be rejected (any resolved value will be ignored).

Example
ui.showLoading(true);
BloodhoundPromise.call(someMethod)
  .then(…)
  .finally(() => ui.showLoading(false));
Parameters:
Name Type Attributes Description
callback function <optional>

Method to invoke when the promise settles. The method will be passed the resolved value or rejection reason.

Returns:

A new promise.

Type
BloodhoundPromise

isRejected() → {boolean}

Source:

Returns whether the promise has been rejected.

Example
BloodhoundPromise.reject().isRejected(); // true
BloodhoundPromise.delay(1000).isRejected(); // false
BloodhoundPromise.resolve(123).isRejected(); // false
Returns:

Whether the promise has been rejected.

Type
boolean

isResolved() → {boolean}

Source:

Returns whether the promise has been resolved.

Example
BloodhoundPromise.reject().isResolved(); // false
BloodhoundPromise.delay(1000).isResolved(); // false
BloodhoundPromise.resolve(123).isResolved(); // true
Returns:

Whether the promise has been resolved.

Type
boolean

isSettled() → {boolean}

Source:

Returns whether the promise has been resolved or rejected.

Example
BloodhoundPromise.reject().isSettled(); // true
BloodhoundPromise.resolve().isSettled(); // true
BloodhoundPromise.delay(1000).isSettled(); // false
Returns:

Whether the promise has been resolved or rejected.

Type
boolean

notify() → {BloodhoundPromise}

Source:
Deprecated:
  • Not used in Bloodhound.

Does nothing. Exists for backwards-compatibility.

Returns:

A new promise that matches the parent promise.

Type
BloodhoundPromise

spread(callbackopt) → {BloodhoundPromise}

Source:

When a promise is resolved with an array, spread will invoke the given success callback by passing each element in the array for each expected argument.

Example
BloodhoundPromise.all([
  'value for arg 1',
  BloodhoundPromise.call(getValueForArg2),
  BloodhoundPromise.resolve(getValueForArg3()),
]).spread((arg1, arg2, arg3) => { … });
Parameters:
Name Type Attributes Description
callback function <optional>

Method to invoke with the array of resolved values passed in as arguments.

Returns:

A new promise.

Type
BloodhoundPromise

tap(callbackopt) → {BloodhoundPromise}

Source:

Used for side effects. Invokes the specified callback only if the promise resolves. If the callback returns a promise, the promise chain will wait for that promise to settle but will not propagate the settled value to the next promise in the chain. Instead, the original resolved value will always be propagated.

Example
BloodhoundPromise.call(someMethod, 'arg')
  .tap(result => log.info('method succeeded', result))
  .then(result => { … });
Parameters:
Name Type Attributes Description
callback function <optional>

The method to invoke when the promise resolves. Will be passed the resolved value. Nothing this callback does will affect the next promise in the chain, which will always be provided with the original resolved value.

Returns:

A new promise.

Type
BloodhoundPromise

then(onFulfilledopt, onRejectedopt) → {BloodhoundPromise}

Source:

Invokes one of the specified callbacks when the promise settles.

Examples
BloodhoundPromise.call(someMethod)
  .then(onSuccess);
BloodhoundPromise.call(someMethod)
  .then(onSuccess, onFailure);
Parameters:
Name Type Attributes Description
onFulfilled function <optional>

Method to invoke when the promise resolves. Will be passed the resolved value.

onRejected function <optional>

Method to invoke when the promise rejects. Will be passed the rejection reason.

Returns:

A new promise.

Type
BloodhoundPromise

timeout(ms, erroropt) → {BloodhoundPromise}

Source:

Rejects the returned promise if the given promise fails to settle within the specified period. If the given promise settles within the specified period then the returned value will be resolved or rejected to match.

Example
BloodhoundPromise.call(someMethod, 'arg')
  .timeout(10000, new Error('operation timed out'))
  .then(…);
  .catch(…);
Parameters:
Name Type Attributes Description
ms number

The number of milliseconds to wait before rejecting the promise with the specified reason.

error any <optional>

The optional reason the promise should be rejected with if the timeout period elapses.

Returns:

A new promise.

Type
BloodhoundPromise

unwrap() → {Promise}

Source:

Provides an instance of the original Promise implementation that matches the resolved or rejected state of this BloodhoundPromise.

Example
BloodhoundPromise.call(someMethod, 'arg')
  .unwrap() // as original Promise
  .catch(console.error);
Returns:

An instance of the original Promise settled to match this BloodhoundPromise.

Type
Promise

value() → {any}

Source:

Returns the resolved value or rejection reason.

Example
BloodhoundPromise.resolve(123).value(); // 123
BloodhoundPromise.delay(10, 123).value(); // undefined (not yet settled)
BloodhoundPromise.reject(new Error('oops')).value(); // <Error: oops>
Returns:

The resolved value or rejection reason. If the Promise has not been settled, returns undefined.

Type
any