Gathering detailed insights and metrics for @nevware21/ts-async
Gathering detailed insights and metrics for @nevware21/ts-async
Gathering detailed insights and metrics for @nevware21/ts-async
Gathering detailed insights and metrics for @nevware21/ts-async
npm install @nevware21/ts-async
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
3 Stars
141 Commits
2 Forks
1 Watching
14 Branches
2 Contributors
Updated on 18 Nov 2024
TypeScript (96.56%)
JavaScript (3.44%)
Cumulative downloads
Total Downloads
Last day
-0.1%
62,798
Compared to previous day
Last week
3%
335,821
Compared to previous week
Last month
10.5%
1,393,285
Compared to previous month
Last year
502.8%
11,725,357
Compared to previous year
1
39
This package provides support for asynchronous development with a Promise based task Scheduler, several different Promise implementations (synchronous, idle, asynchronous and native runtime wrappers), await helpers, and aliases all built and tested using TypeScript. One of the primary focuses of this package is to provide support for the creation of code that can be better minified, resulting in a smaller runtime payload which can directly assist with Page Load performance.
The Promise based Task Scheduler supports the serialized execution of tasks using promises to control when the next task should be executed (after the previous task completes), this leverages the supplied Promise implementations so that you can easily create an Idle Task Scheduler which executes the tasks using requestIdleCallback
when using the createIdlePromise
implementation.
All of the provided Promise implementations support usage patterns via either
await
or with the included helper functions (doAwait
,doFinally
,doAwaitresponse
), you can also mix and match them (use both helper andawait
) as required by your use cases.
See the documentation generated from source code via typedoc for a full list and details of all of the available types, functions, interfaces with included examples.
See Browser Support for details on the supported browser environments.
Type / Function | Since | Details |
---|---|---|
Promise based Scheduler | ||
createTaskScheduler | Create a Task Scheduler using the optional promise implementation and scheduler name. The newPromise can be any value promise creation function, where the execution of the queued tasks will be processed based on how the promise implementation processes it's chained promises (asynchrounsly; synchronously; idle processing, etc) There is no limit on the number of schedulers that you can create, when using more than one scheduler it is recommended that you provide a name to each scheduler to help identify / group promises during debugging. | |
ITaskScheduler | 0.2.0 | Defines a Task Scheduler that uses IPromise implementations to serialize the execution of the tasks. Each added task will not get executed until the previous task has completed. |
StartQueuedTaskFn | 0.2.0 | Identifies the function to call to start and execute the task when its ready to be executed. |
Interfaces | ||
IPromise | This package uses and exports the IPromise<T> interface which extends both the PromiseLike<T> and Promise<T> to provide type compatibility when passing the Promises created with this package to any function that expects a Promise (including returning from an async function ). As part of it's definition it exposes an [optional] string status to represent the current state of the Promise . These values include pending , resolved rejected and resolving which is a special case when a Promise is being resolved via another Promise returned via the thenable onResolved / onRejected functions. | |
AwaitResponse | This interface is used to represent the result whether resolved or rejected when using the doAwaitResponse , this function is useful when you want to avoid creating both a resolved and rejected functions, as this function only requires a single callback function to be used which will receive an object that conforms to this interface. | |
IWhileState | 0.5.0 | The current state of the while loop while processing the callback function, this is passed to eht callback function. |
IPromiseResult | 0.5.0 | The result of a promise. It can either be fulfilled with a value, or rejected with a reason. |
Alias | ||
createPromise createAllPromise createAllSettledPromise createAnyPromise createRacePromise createRejectedPromise createResolvedPromise setCreatePromiseImpl | 0.5.0 0.5.0 0.5.0 | These function use the current promise creator implementation that can be set via Unless otherwise set this defaults to the createNativePromise implementation, to provide a simplified wrapper around any native runtime Promise support. Available implementation: By using these aliases, it's possible to switch between any of these implementations as needed without duplicating your code. This will not change any existing promises, it only affects new promises. |
createNativePromise createNativeAllPromise createNativeAllSettledPromise createNativeAnyPromise createNativeRacePromise createNativeRejectedPromise createNativeResolvedPromise | 0.5.0 0.5.0 0.5.0 | These are effectively wrappers around the runtime Promise class, so this is effectivly the same as new Promise(...) but as a non-global class name it can be heavily minified to something like a(...) . These wrappers also add an accessible status property for identifying the current status of this promise. However, the status property is NOT available on any returned chained Promise (from calling then , catch or finally ) |
Asynchronous Promise | ||
createAsyncPromise createAsyncAllPromise createAsyncAllSettledPromise createAsyncAnyPromise createAsyncRacePromise createAsyncRejectedPromise createAsyncResolvedPromise | 0.5.0 0.5.0 0.5.0 | Provides an implementation of the Promise contract that uses timeouts to process any chained promises (returned by then(...) , catch(...) , finally(...) ), when creating the initial promise you can also provide (override) the default duration of the timeout (defaults to 0ms) to further delay the execution of the chained Promises., but can also be provided) to process any chained promises (of any type) |
Synchronous Promise | ||
createSyncPromise createSyncAllPromise createSyncAllSettledPromise createSyncAnyPromise createSyncRacePromise createSyncRejectedPromise createSyncResolvedPromise | 0.5.0 0.5.0 0.5.0 | Also implements the Promise contract but will immediately execute any chained promises at the point of the original promise getting resolved or rejected, or if already resolved, rejected then at the point of registering the then , catch or finally |
Idle Promise | ||
createIdlePromise createIdleAllPromise createIdleAllSettledPromise createIdleAnyPromise createIdleRacePromise createIdleRejectedPromise createIdleResolvedPromise | 0.5.0 0.5.0 0.5.0 | Implements the Promise contract and will process any chained promises using the available requestIdleCallback (with no timeout by default - but can also be changes by setDetaultIdlePromiseTimeout ). And when requestIdleCallback is not supported this will default to using a timeout via the scheduleIdleCallback from @nevware21/ts-utils |
Timeout | ||
createTimeoutPromise | Creates a Promise instance that resolve or reject after the specified timeout. | |
Helpers | ||
createTimeoutPromise | 0.5.0 | Creates a Promise instance that resolve or reject after the specified timeout. |
doAwait | Helper which handles await "handling" via callback functions to avoid the TypeScript boilerplate code that is added for multiple branches. Internal it handles being passed an IPromise or a result value so you avoid needing to test whether the result you have is also a Promise .It takes three (3) optional callback functions for resolved , rejected and finally . | |
doAwaitResponse | Helper which handles await "handling" via a single callback where resolved and rejected cases are handled by the same callback, this receives an AwaitResponse object that provides the value or reason and a flag indicating whether the Promise was rejected | |
doFinally | Helper to provide finally handling for any promise using a callback implementation, analogous to using try / finally around an await function or using the finally on the promise directly | |
arrForEachAsync | 0.5.0 | Performs an asynchronous for loop where the calling function may return an IPromise which must be fulfilled before the next iteration is called. |
doWhileAsync | 0.5.0 | Performs a while loop where the calling function may return an IPromise which must be fulfilled before the next iteration is called. |
iterForOfAsync | 0.5.0 | Iterates over the iterator where the calling function may return an IPromise which must be fulfilled before the next iteration is called. |
Polyfill | ||
PolyPromise | 0.5.0 | A full polyfill for the Promise class |
All promise implementations are validated using TypeScript with async
/ await
and the internal helper functions doAwait
, doFinally
and doAwaitResponse
helpers. Usage of the doAwait
or doAwaitResponse
is recommended as this avoids the additional boiler plate code that is added by TypeScript when handling the branches in an async
/ await
operations, this does however, mean that your calling functions will also need to handle this async
operations via callbacks rather than just causing the code path to "halt" at the await
and can therefore may be a little more complex (depending on your implementation).
However, you are NOT restricted to only using
await
ORdoAwait
they can be used together. For example your public API can still be defined as asynchronous, but internally you could usedoAwait
1async function myApi() 2{ 3 await doAwait(thePromise, (result) => { ... }, (reason) => { ... }); 4}
All implementations will "emit/dispatch" the unhandled promise rejections event (unhandledRejection
(node) or unhandledrejection
) (if supported by the runtime) using the standard runtime mechanisms. So any existing handlers for native (new Promise
) unhandled rejections will also receive them from the idle
, sync
and async
implementations. The only exception to this is when the runtime (like IE) doesn't support this event in those cases "if" an onunhandledrejection
function is registered it will be called and if that also doesn't exist it will logged to the console (if possible).
The package provides a simple polyfill wrapper which is built around the asynchronous
promise implementation which is tested and validated against the standard native (Promise()
) implementations for node, browser and web-worker to ensure compatibility.
This library plans to maintain ES5 compatibility for all versions of v0.x and v1.x releases
Future versions of this library starting at version 2.x are planned to lift and remove the internal polyfills to support the new targetted baseline once it is defined. ie. It may or may not be ES6 depending on the runtime landscape and requests received.
When we release v2.x the supported browser matrix will also shift as required to match the defined language level supported at that time.
Install the npm packare: npm install @nevware21/ts-async --save
It is suggested / recommended that you use the following definition in your
package.json
so that you are compatible with any future releases as they become available we do not intend to make ANY known breaking changes moving forward until v2.x1"@nevware21/ts-async": ">= 0.5.3 < 2.x"
And then just import the helpers and use them.
1import { createTaskScheduler } from "@nevware21/ts-async"; 2import { scheduleTimeout } from "@nevware21/ts-utils"; 3 4let scheduler = createTaskScheduler(); 5 6// Schedule (and start) task 1 using native promise 7// Because this is a new scheduler there are no other 8// pending tasks so this will be started synchronously 9let task1 = scheduler.queue(() => { 10 return new Promise((resolve) => { 11 setTimeout(() => { 12 resolve(42); 13 }, 100); 14 }); 15}); 16 17// task1.status; => "pending" (and running) 18 19// Schedule task 2 using helper function 20// The startTask function for task2 will not be called 21// until task1 has completed 22let task2 = scheduler.queue(() => { 23 return createPromise((resolve) => { 24 scheduleTimeout(() => { 25 resolve(21); 26 }, 100); 27 }); 28}); 29 30// task2.status; => "pending" (not running) 31 32await task1; 33// task1.status => "resolved" 34// task2.status => "pending" (but running)
1import { createPromise } from "@nevware21/ts-async"; 2import { scheduleTimeout } from "@nevware21/ts-utils"; 3 4const myPromise = createPromise((resolve, reject) => { 5 scheduleTimeout(() => { 6 resolve("foo"); 7 }, 300); 8}); 9 10myPromise 11 .then(handleFulfilledA, handleRejectedA) 12 .then(handleFulfilledB, handleRejectedB) 13 .then(handleFulfilledC, handleRejectedC) 14 .catch(handleRejectedAny); 15 16// Create a new promise that resolves with an inner promise that will auto resolve after 1 second 17createPromise((resolveOuter) => { 18 resolveOuter( 19 createPromise((resolveInner) => { 20 scheduleTimeout(resolveInner, 1000); 21 }) 22 ); 23}); 24 25doAwait(myPromise, (result) => { 26 // Handle the result this would normally be 27 // let result = await myPromise; 28}, (reason) => { 29 // Handle cases when the `myPromise` is rejected 30 // Using await you would handle this via try / catch 31});
While the examples above are using the createPromise
you can directly use the createSyncPromise
, createAsyncPromise
, createIdlePromise
or createNativePromise
, you can also mix and match them (ie. they don't all have to be the same implementation). The createPromise
alias is provided to enable switching the underlying Promise implementation without changing any of your code.
General support is currently set to ES5 supported runtimes and higher.
Internal polyfills are used to backfill ES5 functionality which is not provided by older browsers.
Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ |
Note: A PolyFill
PolyPromise
provides the standard promise implementations for IE and ES5+ environments.
Read our contributing guide to learn about our development process, how to propose bugfixes and improvements, and how to build and test your changes.
No vulnerabilities found.
No security vulnerabilities found.