asyncDeferrer 
Creates a deferrer, which is a function that behaves very similar to a deferred object: it allows the get and the resolve of a promise.
It allows the creation of more expressive tests. The reason for this library is just matter of expressiveness.
Quick Use
Install with npm:
npm install async-deferrerUse in your code:
makeAsyncDeferrer()
It creates a function that can be used as a defer.
const asyncDeferrer = asyncDeferrer(resolutionValue?: any): Promise
The resulting function returns always a promise that will be satisfied when the function is called with an argument.
const asyncDeferrer = // you can get the promise at any moment as followsconst promise = // it resolves the promise with the given value // you can await the promise as followsawait promise// or directly using a function callawait The promise is resolved once, further invokes with other arguments are ignored.
You can call to the asyncDeferrer function as many times as you want.
asyncDeferrer.reject(rejectionValue): Promise
You can reject the promise if you consider convenient:
asyncDeferrer try await catch error // logs 'promise rejected' consoleBecause the promise is resolved once, further invokes with other arguments are ignored. Further invokes to resolve the promise are also ignored.
Alternatives
There are other libreries or ways that could help you to writte the desired asynchronous code.
(pDefer)[https://github.com/sindresorhus/p-defer]
It is a library from (Sindre Sorhus)[https://github.com/sindresorhus) part of his large list of p-*.
The code for the same presentation shouwn before could be something like:
Plain promises
The same behaviour can be achieved with plain promises.
Why asyncDeferrer instead of Promises or defer
It is cleaner an easier to read.
If we compare all three presented cases:
// asyncDeferrer// pDefertimeoutDeferred// PromiseThe first of three writings is the most easy to enderstand version. Just reading we knew that we are telling that the timeout is finished. The promise version could be rewrote as:
// rewrote of Promise versionconst timeoutFinished = { }But it still has the new Promise(() => {}) boilerplate code
and not always easy to use.
Using asyncDeferrer as checkpoints
It in fact is the intention of this library, to ensure that the execution flow is what we expect.
See also
-
async-barrier: it is the library that inspired this one, and originally was designed to ensure that multiple async functions reaches the same point at the same time
-
pDefer: traditional defer library generated from the system Promise
-
p-*: lots of Promise utilities created by the guy behind
pDefer.