1.0.0 • Published 7 months ago

resettable-defer v1.0.0

Weekly downloads
-
License
WTFPL OR CC0-1.0
Repository
-
Last release
7 months ago

resettable-defer

For when you need a Promise.defer, but you need to use it more than once, eg. because there is some code that needs to subscribe whatever the next (periodic) 'activation' is.

It's kind of like an EventEmitter with a single event, but less hassle to use with Promises.

Example

const resettableDefer = require("resettable-defer");

let defer = resettableDefer({ autoReset: true });

/* The below configuration of intervals should result in approximately 5 instances
   of "Activated!" getting logged at once, every half a second, forever. */

setInterval(async () => {
	await defer.await();
	console.log("Activated!");
}, 100);

setInterval(async () => {
	defer.resolve();
}, 500);

API

defer = resettableDefer(options)

Creates a new resettable defer. Options:

  • autoReset: Defaults to false. Automatically 'reset' the defer once it resolves or rejects. - When false: if you defer.await() after the defer has already settled, it will immediately settle with the existing result, and you need to call defer.reset() manually to use it again. - When true: after the defer settles, it is automatically reset, and can immediately be used again; the next defer.await() calls will track a new internal defer.

defer.await()

Returns a Promise that resolves or rejects when (the current instance of) the defer does. This is the equivalent of the defer.promise property that you will find in most defer implementations, but here it is a function instead of just a static property.

If (the current instance of) the defer is already resolved or rejected, then the returned Promise will also be immediately resolved or rejected, ie. the results are essentially cached.

defer.resolve(value)

Resolves the defer (and all Promises tracking it) with the specified value.

defer.reject(error)

Rejects the defer (and all Promises tracking it) with the specified error, which should be an Error instance or subclass.

defer.track(promise)

Causes the defer to track an externally-provided promise; when that Promise resolves or rejects, so will the defer and all Promises tracking it.

defer.reset()

'Resets' the defer, so that it can be used anew. Note that if you have one or more Promises tracking the previous instance, and that instance hadn't settled yet, these Promises will never resolve!