npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

xrtlibrary-async

v1.0.18

Published

Asynchronous helpers module of XRT library.

Downloads

65

Readme

XRTLibrary-Async

Introduction

This library contains several asynchronous mechanism implementations which can help you write complex JavaScript asynchronous programs.

Available features:

  • An advanced Promise.race() which also returns the associated Promise object.
  • Asynchronous queue.
  • Deferred-style conditional synchronizers.
  • Asynchronous semaphore.
  • Asynchronous lock.

Deprecated features:

  • Asynchronous program flows (which can be replaced by async/await).

Installation

To install this package, you can use NPM by typing following command:

npm install xrtlibrary-async --save

Then you can import this library in your JavaScript code:

const XRTLibAsync = require("xrtlibrary-async");

Examples

Download this package and see the "examples" directory.

API

(Module) Asynchronize.Loop (Deprecated)

Introduction: This module contains several functions that can help you create asynchronous program flows, including:

  • for statement.
  • while statement.
  • do...while statement.

Warning(s):

  • This module has been deprecated.
  • The existence of this module is ONLY for compatible. You shall NOT use any API of this module in new application.
  • Use JavaScript's native async/await mechanism to replace this module.

RunAsynchronousLoop(fn)

Run a loop asynchronously.

Parameter(s):

  • fn (() => Promise): The loop function.

Return value:

  • (Promise) The promise object.

Example:

let counter = 0;
XRTLibAsync.Asynchronize.Loop.RunAsynchronousLoop(function() {
    console.log(++counter);
    return XRTLibAsync.Asynchronize.Timeout.CreateTimeoutPromise(1000);
});
//  Output (1000ms per line):
//    1
//    2
//    3
//    ...

Equivalent using async/await:

let counter = 0;
while(true) {
    console.log(++counter);
    await XRTLibAsync.Asynchronize.Timeout.CreateTimeoutPromise(1000);
}

RunAsynchronousForNext(fnCondition, fnNext, fnBody)

Run a for-next statement asynchronously.

Parameter(s):

  • fnCondition (() => Boolean): The condition function.
  • fnNext (() => void): The next function.
  • fnBody (() => Promise): The body function.

Return value:

  • (Promise) The promise object.

Example:

let i = 1;
XRTLibAsync.Asynchronize.Loop.RunAsynchronousForNext(
    function() {
        return i <= 3;
    },
    function() {
        ++i;
    },
    function() {
        console.log(i);
        return XRTLibAsync.Asynchronize.Timeout.CreateTimeoutPromise(1000);
    }
);
//  Output (1000ms per line):
//    1
//    2
//    3

Equivalent using async/await:

for (let i = 1; i <= 3; ++i) {
    console.log(i);
    await XRTLibAsync.Asynchronize.Timeout.CreateTimeoutPromise(1000);
}

RunAsynchronousDoWhile(fnCondition, fnBody)

Run a do-while statement asynchronously.

Parameter(s):

  • fnCondition (() => Boolean): The condition function.
  • fnBody (() => Promise): The body function.

Return value:

  • (Promise) The promise object.

Example:

let i = 1;
XRTLibAsync.Asynchronize.Loop.RunAsynchronousDoWhile(
    function() {
        return i < 1;
    },
    function() {
        console.log(i);
        return XRTLibAsync.Asynchronize.Timeout.CreateTimeoutPromise(1000);
    }
);
//  Output:
//    1

Equivalent using async/await:

let i = 1;
do {
    console.log(i);
    await XRTLibAsync.Asynchronize.Timeout.CreateTimeoutPromise(1000);
} while(i < 1);

(Module) Asynchronize.Waterfall (Deprecated)

Introduction: This module contains a helper function that can help you create generic asynchronous waterfall program flows.

Warning(s):

  • This module has been deprecated.
  • The existence of this module is ONLY for compatible. You shall NOT use any API of this module in new application.
  • Use JavaScript's native async/await mechanism to replace this module.

CreateWaterfallPromise(tasks, [strictMode])

Create a waterfall promise.

Parameter(s):

  • tasks ((() => Promise)[]): The tasks.
  • strictMode (Boolean): True if a task function must return with a Promise object.

Return value:

  • The waterfall promise (resolve with the the value of the lastest task).

Example:

XRTLibAsync.Asynchronize.Waterfall.CreateWaterfallPromise([
    function() {
        console.log("Hello!");
        return XRTLibAsync.Asynchronize.Timeout.CreateTimeoutPromise(1000);
    },
    function() {
        console.log("World!");
        return Promise.resolve();
    }
]);
//  Output:
//    Hello!
//    World!  (1000ms later)

Equivalent using async/await:

console.log("Hello!");
await XRTLibAsync.Asynchronize.Timeout.CreateTimeoutPromise(1000);
console.log("World!");

(Module) Asynchronize.Preempt

Introduction: The function that this module provides is similar to Promise.race(). But instead of returning the resolved value only, this module also gives the Promise object so that you can know which asynchronous task finishs the first.

(Class) PreemptResolve

Preempt resolve container.

preemptrsv.getValue()

Get the value.

Return value:

  • (*) The value.
preemptrsv.getPromiseObject()

Get the promise object.

Return value:

  • (Promise) The promise object.

(Class) PreemptReject

Preempt reject container.

preemptrej.getReason()

Get the reason.

Return value:

  • (*) The reason.
preemptrej.getPromiseObject()

Get the promise object.

Return value:

  • (Promise) The promise object.

CreatePreemptivePromise(tasks)

Create a preemptive promise (the first completed task will take over the promise).

Note(s):

  • Generally, when more than one tasks are in settled states, the task which has the smallest index in tasks array would be returned. But you shall NOT rely on this (this behavior may changes in future releases of this library.).
  • If the returned promise object rejects, an instance of PreemptReject class would be provided as the reject reason.

Parameter(s):

  • tasks (Promise[]): The tasks.

Return value:

  • (Promise<PreemptResolve>) The promise object.

Example:

let p1 = XRTLibAsync.Asynchronize.Timeout.CreateTimeoutPromise(100);    //  This promise object resolves after 100ms.
let p2 = XRTLibAsync.Asynchronize.Timeout.CreateTimeoutPromise(500);    //  This promise object resolves after 500ms.
let p3 = XRTLibAsync.Asynchronize.Timeout.CreateTimeoutPromise(1000);   //  This promise object resolves after 1000ms.
let rsv = await XRTLibAsync.Asynchronize.Preempt.CreatePreemptivePromise([p1, p2, p3]);
let p = rsv.getPromiseObject();
if (p == p1) {
	console.log("Promise 1 preempted!");
} else if (p == p2) {
	console.log("Promise 2 preempted!");
} else if (p == p3) {
	console.log("Promise 3 preempted!");
} else {
    throw new Error("Unreachable.");
}
//  Output:
//    Promise 1 preempted!

(Module) Asynchronize.Timeout

Introduction: This module implements asynchronous delay functions.

(Constant) SLIMTIMEOUT_STATUS_{AWAIT, CANCELLED, TIMEOUTED}

Slim timeout wait handle status.

(Type) TSlimTimeoutWaitHandle : Object

Slim timeout wait handle.

Properties:

  • status (Number): Current status:
    • SLIMTIMEOUT_STATUS_AWAIT: Waiting for the timeout timer to be expired.
    • SLIMTIMEOUT_STATUS_TIMEOUTED: The timeout timer expired.
    • SLIMTIMEOUT_STATUS_CANCELLED: Cancelled before the timeout timer expires.
  • handle (Promise<TSlimTimeoutWaitHandle>): The wait handle (a promise object that resolves with this wait handle when it leaves SLIMTIMEOUT_STATUS_AWAIT status).
  • cancel (() => void): The cancellator function.

(Class) TimeoutPromiseError

Timeout promise error.

Extend(s):

  • Error

(Class) TimeoutPromiseOperationCancelledError

Timeout promise operation cancelled error.

Extend(s):

  • TimeoutPromiseError

CreateTimeoutPromise(timespan, [value])

Create a timeout promise which resolves after specific duration (timespan).

Parameter(s):

  • timespan (Number): The duration (timespan, unit: milliseconds).
  • value (*): (Optional) The resolve value (default = null).

Return value:

  • (Promise) The promise object (resolves when timeouted, never rejects).

Example:

console.log("Hello!");
console.log(await XRTLibAsync.Asynchronize.Timeout.CreateTimeoutPromise(1000, "World!");
//  Output:
//    Hello!
//    World!  (1000ms later)

CreateTimeoutPromiseEx(timespan, cancellator, [value])

Create a timeout promise which resolves after specific duration (timespan) with a cancellable mechanism.

Exception(s):

  • TimeoutPromiseOperationCancelledError: Raised when the cancellator was activated.

Parameter(s):

  • timespan (Number): The duration (timespan, unit: milliseconds).
  • cancellator (Synchronize.Conditional.ConditionalSynchronizer): The cancellator.
  • value (*): (Optional) The resolve value (default = null).

Return value:

  • (Promise) The promise object (resolves when timeouted, rejects if error occurred).

Example:

let cancellator = new XRTLibAsync.Synchronize.Conditional.ConditionalSynchronizer();
XRTLibAsync.Asynchronize.Timeout.CreateTimeoutPromiseEx(5000, cancellator).then(function() {
    throw new Error("Unreachable.");
}).catch(function(error) {
    if (error instanceof XRTLibAsync.Asynchronize.Timeout.TimeoutPromiseOperationCancelledError) {
        console.log("Timeout timer has been cancelled.");
    } else {
        throw error;
    }
});
//  Cancel after 1000ms.
setTimeout(function() {
    cancellator.fullfill();
}, 1000);
//  Output:
//    Timeout timer has been cancelled.  (1000ms after startup)

WaitTimeoutSlim(timespan)

Wait for timeout.

Parameter(s):

  • timespan (Number): The timeout (unit: milliseconds).

Return value:

  • (TSlimTimeoutWaitHandle) The slim timeout wait handle.

(Module) Event

Introduction: This module implements several functions that helps you handle events.

(Class) EventWaiterError

Event waiter error.

Extend(s):

  • Error

(Class) EventWaiterOperationCancelledError

Event waiter operation cancelled error.

Extend(s):

  • EventWaiterError

WaitEvent(handler, name, [cancellator])

Wait for an event.

Exception(s):

  • EventWaiterOperationCancelledError - Raised when the cancellator was activated.

Parameter(s):

  • handler (EventEmitter): The event handler.
  • name (String): The event name.
  • cancellator (Synchronize.Conditional.ConditionalSynchronizer): (Optional) The cancellator.

Return value:

  • (Promise<Array>) The promise object (resolves with the event arguments if succeed, rejects if error occurred).

Example:

let server = net.createServer();
let listenWaitHandler = XRTLibAsync.Event.WaitEvent(server, "listening");
server.listen(8080);
await listenWaitHandler;
console.log("Server listened!");
let server = net.createServer();
let cts = new XRTLibAsync.Synchronize.Conditional.ConditionalSynchronizer();
let wh1 = XRTLibAsync.Event.WaitEvent(server, "listening", cts);
let wh2 = XRTLibAsync.Event.WaitEvent(server, "error", cts);
server.listen(8080);
let rsv = await XRTLibAsync.Asynchronize.Preempt.CreatePreemptivePromise([wh1, wh2]);
cts.fullfill();
let wh = rsv.getPromiseObject();
if (wh == wh1) {
    console.log("Server listened!");
    //  Handle connections here.
} else if (wh == wh2) {
    console.log("Unable to bind!");
    server.close();
    //  Handle server close here.
} else {
    throw new Error("Unreachable.");
}

(Module) Promise

Introduction: This module implements several data structures that are related to JavaScript's promise mechanism.

(Constant) PROMISEQUEUEOP_PUSH

Indicates a push (put()) operation to a PromiseQueue object.

(Constant) PROMISEQUEUEOP_POP

Indicates a pop (get() and getSync()) operation to a PromiseQueue object.

(Class) PromiseWrapper<T>

Promise context wrapper.

new PromiseWrapper(resolve, reject)

Constructs an object.

Parameter(s):

  • resolve ((value: T) => void): The resolve function.
  • reject (*(reason: ) => void): The reject function.
pw.getResolveFunction()

Get the resolve function.

Return value:

  • ((value: T) => void): The resolve function.
pw.getRejectFunction()

Return value:

  • (*(reason: ) => void): The reject function.

(Class) PromiseQueue<T>

Promise queue.

Extend(s):

  • EventEmitter
(Event) 'change'

Promise queue change event.

Note(s):

  • This event would only be emitted when the count of pending items were changed.
  • This event wouldn't be emitted if you put an item and there is already some get() operations in waiting (In this situation, the waiting get() operation would be answered with the item immediately instead of inserting the item to the pending items queue).

Parameter(s):

  • type (Number): The action type (one of PROMISEQUEUEOP_*).
  • item (*): The item related to the action.
pq.put(item)

Put an item to the queue.

Parameter(s):

  • item (T): The item.
pq.get([cancellator])

Get an item from the queue.

Exception(s):

  • PromiseQueue.OperationCancelledError: Raised when the cancellator was activated.

Parameter(s):

  • cancellator (Synchronize.Conditional.ConditionalSynchronizer): (Optional) The cancellator.

Return value:

  • (Promise<T>) The promise object (resolves with the item if succeed, rejects if error occurred).

Example:

let queue = new XRTLibAsync.Promise.PromiseQueue();
(async function() {
    console.log(await queue.get());
})();
(async function() {
    for (let i = 1; i <= 5; ++i) {
        queue.put(i);
        await XRTLibAsync.Asynchronize.Timeout.CreateTimeoutPromise(1000);
    }
})();
pq.getSync()

Get an item from the queue synchronously.

Note(s):

  • An error will be thrown if the queue has no item.
  • It highly NOT recommended to use this method with both wait() and clear() method.

Exception(s):

  • PromiseQueue:InvalidOperationError: Raised when this queue is empty.

Return value:

  • (T) The item.
pq.getLength()

Get the count of in-queue items (queue length).

Return value:

  • (Number) The item count.
pq.wait([cancellator])

Wait for an item to be available.

Parameter(s):

  • cancellator (Synchronize.Conditional.ConditionalSynchronizer): (Optional) The cancellator.

Return value:

  • The promise object (resolves when available, rejects if error occurred).
pq.clear()

Clear all in-queue items.

(Class) PromiseQueue.Error

Promise queue error.

Extend(s):

  • Error

(Class) PromiseQueue.OperationCancelledError

Promise queue operation cancelled error.

Extend(s):

  • PromiseQueue.Error

(Class) PromiseQueue.InvalidOperationError

Promise queue invalid operation error.

Extend(s):

  • PromiseQueue.Error

(Class) PromiseQueue2<T>

Promise queue (version 2).

Extend(s):

  • EventEmitter
(Constant) PromiseQueue2.CHANGETYPE_PUSH

Indicates a push (push()) operation.

(Constant) PromiseQueue2.CHANGETYPE_POP

Indicates a pop (pop() and popWithReceipt()) operation.

(Constant) PromiseQueue2.CHANGETYPE_UNPOP

Indicates an unpop (unpop()) operation.

(Event) 'change'

Promise queue change event.

Note(s):

  • This event would only be emitted when the count of pending items were changed.

Parameter(s):

  • type (Number): The action type (one of PromiseQueue2.CHANGETYPE_*).
  • item (*): The item related to the action.
(Property) pq2.length (readonly)

The count of queued items.

Exception(s):

  • PromiseQueue.InvalidOperationError: Raised when tries to assign value to this property.
pq2.isWaitingForReceipt()

Get whether this object is waiting for a receipt.

Return value:

  • True if so.
pq2.pop([cancellator])

Pop an item asynchronously.

Exception(s):

  • PromiseQueue.OperationCancelledError: Raised when the cancellator was activated.

Parameter(s):

  • cancellator (Synchronize.Conditional.ConditionalSynchronizer): (Optional) The cancellator.

Return value:

  • (Promise<T>) The promise object (resolves with the item when succeed, rejects when error occurred).
pq2.popWithReceipt(receipt, [cancellator])

Pop an item asynchronously with receipt mechanism.

Exception(s):

  • PromiseQueue.OperationCancelledError: Raised when the cancellator was activated.

Parameter(s):

  • receipt (?PromiseQueue2.Receipt): The receipt (NULL if not set).
  • cancellator (Synchronize.Conditional.ConditionalSynchronizer): (Optional) The cancellator.

Return value:

  • (Promise<T>) The promise object (resolves with the item when succeed, rejects when error occurred).

Example:

let queue = new XRTLibAsync.Promise.PromiseQueue2();

async function RunWorker(workerId) {
    while(true) {
        let receipt = new XRTLibAsync.Promise.PromiseQueue2.Receipt();
        let task = await queue.popWithReceipt(receipt);
        if (task === null) {
            console.log("Worker " + workerId.toString() + " ended.");
            receipt.getDeclineSynchronizer().fullfill();  //  Reject the popped item (the item would be unpopped to the queue).
            break;
        } else {
    	    console.log("Worker " + workerId.toString() + ", task " + task.toString());
    	    receipt.getAcceptSynchronizer().fullfill();   //  Accept the popped item.
    	    await XRTLibAsync.Asynchronize.Timeout.CreateTimeoutPromise(1000 * Math.random());
        }
    }
}

//  Run workers.
RunWorker(1);
RunWorker(2);

//  Add tasks.
function (let i = 1; i <= 100; ++i) {
    queue.push(i);
}
queue.push(null);
pq2.unpop(item)

Unpop an item.

Note(s):

  • This method can't be called when this object is waiting for a receipt.

Exception(s):

  • PromiseQueue.InvalidOperationError: Raised this object is still waiting for a receipt.

Parameter(s):

  • item (T) - The item.
pq2.push(item)

Push an item.

Parameter(s):

  • item (T) - The item.
pq2.clear()

Clear all items.

(Class) PromiseQueue2.Receipt

Promise queue receipt.

receipt.getAcceptSynchronizer()

Get the decline synchronizer.

Return value:

  • (Synchronize.Conditional.ConditionalSynchronizer) The synchronizer.
receipt.getDeclineSynchronizer()

Get the accept synchronizer.

Return value:

  • (Synchronize.Conditional.ConditionalSynchronizer) The synchronizer.
receipt.getReceiptAcknowledgeSynchronizer()

Get the receipt acknowledge.

Return value:

  • (Synchronize.Conditional.ConditionalSynchronizer) The synchronizer.

(Class) PromiseQueue2.Error

Promise queue error.

Extend(s):

  • Error

(Class) PromiseQueue2.OperationCancelledError

Promise queue operation cancelled error.

Extend(s):

  • PromiseQueue2.Error

(Module) Synchronize.Conditional

Introduction: This module implements deferred-style conditional synchronizers.

(Class) ConditionalSynchronizer<T>

Conditional-based synchronizer.

ConditionalSynchronizer.waitAll(synchronizers)

Wait for all conditional synchronizers to be fullfilled.

Parameter(s):

  • synchronizers (ConditionalSynchronizer[]): The synchronizers.

Return value:

  • (Promise<Array>) The promise object (resolves with fullfill values of the synchronizers).
ConditionalSynchronizer.waitAllWithCancellator(synchronizers, cancellator)

Wait for all conditional synchronizers to be fullfilled with a cancellable mechanism.

Exception(s):

  • ConditionalSynchronizer.OperationCancelledError: Raised when the the cancellator was activated.

Parameter(s):

  • synchronizers (ConditionalSynchronizer[]): The synchronizers.
  • cancellator (ConditionalSynchronizer): The cancellator.

Return value:

  • (Promise<Array>) The promise object (resolves with fullfill values of the synchronizers, reject if cancelled).
new ConditionalSynchronizer()

Construct a new object.

cs.wait()

Wait for the condition to be fullfilled.

Return value:

  • (Promise<T>) The promise object (never raise error).

Example:

//  Tasks context.
let sync = new XRTLibAsync.Synchronize.Conditional.ConditionalSynchronizer();

//  In one task:
(async function() {
    console.log(await sync.wait());
})();

//  In another task:
(async function() {
    console.log("Hello world!");
	sync.fullfill("Javascript");
})();

//  Output:
//    Hello world!
//    Javascript
cs.waitWithCancellator(cancellator)

Wait for the condition to be fullfilled with a cancellable mechanism.

Note(s):

  • Once you called this method, a wait handle will be allocated inside the cancellator. It's highly recommended to declare the cancellator as a local variable to avoid memory leak.

Exception(s):

  • ConditionalSynchronizer.OperationCancelledError: Raised when the the cancellator was activated.

Parameter(s):

  • cancellator (ConditionalSynchronizer): The cancellator.

Return value:

  • (Promise<T>) The promise object (reject when cancelled before fullfilled).

Example:

let server = net.createServer();
let syncServerListened = new XRTLibAsync.Synchronize.Conditional.ConditionalSynchronizer();
let syncServerError = new XRTLibAsync.Synchronize.Conditional.ConditionalSynchronizer();
server.on("listening", function() {
    syncServerListened.fullfill(server.address());
});
server.on("error", function(error) {
    syncServerError.fullfill(error);
});
let cts = new XRTLibAsync.Synchronize.Conditional.ConditionalSynchronizer();
let wh1 = syncServerListened.waitWithCancellator(cts);
let wh2 = syncServerError.waitWithCancellator(cts);
server.listen(8080);
let rsv = await XRTLibAsync.Asynchronize.Preempt.CreatePreemptivePromise([wh1, wh2]);
cts.fullfill();  //  Cancel all pending wait handlers.
let wh = rsv.getPromiseObject();
if (wh == wh1) {
    console.log("Server listened!");
    //  Handle connections here.
} else if (wh == wh2) {
    console.log("Unable to bind!");
    server.close();
    //  Handle server close here.
} else {
    throw new Error("Unreachable.");
}
cs.fullfill([data])

Mark the condition as fullfilled.

Note(s):

  • If the synchronizer has already been fullfilled, calling to this method would be ignored.

Parameter(s):

  • data (T): The data (default = null).
cs.unfullfill()

Mark the condition as unfullfilled.

Note(s):

  • If the synchronizer is not fullfilled, calling to this method would be ignored.
cs.isFullfilled()

Get whether the condition was fullfilled.

Return value:

  • (Boolean) True if so.
cs.getFullfilledData()

Get the fullfilled data.

Exception(s):

  • ConditionalSynchronizer.InvalidOperationError: Raised when the synchronizer is not fullfilled.

Return value:

  • (T) The data.

(Class) ConditionalSynchronizer.Error

Conditional synchronizer error.

Extend(s):

  • Error

(Class) ConditionalSynchronizer.OperationCancelledError

Conditional synchronizer operation cancelled error.

Extend(s):

  • ConditionalSynchronizer.Error

(Class) ConditionalSynchronizer.InvalidOperationError

Conditional synchronizer invalid operation error.

Extend(s):

  • ConditionalSynchronizer.Error

(Class) ConditionalSynchronizer.IndexOutOfRangeError

Conditional synchronizer index out of range error.

Extend(s):

  • ConditionalSynchronizer.Error

(Class) MultiConditionalSynchronzier<T>

Switchable multi-conditions synchronizer.

new MultiConditionalSynchronizer(total, initial, [initialData])

Construct a new object.

Parameter(s):

  • total (Number): The condition count.
  • initial (Number): The initial condition index.
  • initialData (T): (Optional) The initial promise data (default = null).
mcs.wait(index)

Wait for specific condition.

Exception(s):

  • ConditionalSynchronizer.IndexOutOfRangeError: Raised when the index is out of range.

Parameter(s):

  • index (Number): The condition index.

Return value:

  • (Promise<T>) The promise object (never raise error).
mcs.waitWithCancellator(index, cancellator)

Wait for specific condition with a cancellable mechanism.

Note(s):

  • Once you called this method, a wait handle will be allocated inside the cancellator. It's highly recommended to declare the cancellator as a local variable to avoid memory leak.

Exception(s):

  • ConditionalSynchronizer.IndexOutOfRangeError: Raised when the index is out of range.
  • ConditionalSynchronizer.OperationCancelledError: Raised when the the cancellator was activated.

Parameter(s):

  • index (Number): The condition index.
  • cancellator (ConditionalSynchronizer): The cancellator.

Return value:

  • (Promise<T>) The promise object (reject when cancelled before fullfilled).
mcs.switch(index, data)

Switch to specific condition.

Exception(s):

  • ConditionalSynchronizer.IndexOutOfRangeError: Raised when the index is out of range.

Parameter(s):

  • index (Number): The condition index.
  • data (T): The fullfill data (default = null).
mcs.getCurrent()

Get current condition.

Return value:

  • (Number) The condition index.
mcs.getTotal()

Get total conditions.

Return value:

  • (Number) The condition count.

(Class) AutomateUnlockConditionalSynchronizer<T>

Conditional synchronizer with automatic unlock functionality.

new AutomateUnlockConditionalSynchronizer()

Construct a new object.

aucs.wait()

Wait for the condition to be fullfilled.

Return value:

  • (Promise<T>) The promise object (never raise error).
aucs.waitWithCancellator(cancellator)

Wait for the condition to be fullfilled with a cancellable mechanism.

Note(s):

  • Once you called this method, a wait handle will be allocated inside the cancellator. It's highly recommended to declare the cancellator as a local variable to avoid memory leak.

Exception(s):

  • ConditionalSynchronizer.OperationCancelledError: Raised when the the cancellator was activated.

Parameter(s):

  • cancellator (ConditionalSynchronizer): The cancellator.

Return value:

  • (Promise<T>) The promise object (reject when cancelled before fullfilled).
aucs.fullfill([data])

Mark the condition as fullfilled.

Parameter(s):

  • data (T): The data (default = null).

(Module) Synchronize.Completion

(Type) TSlimCompletionWaitHandle : Object

Slim completion source wait handle.

Properties:

  • status (Number): Current status:
    • SlimCompletion.STATUS_AWAIT: Waiting for completion enters completed status.
    • SlimCompletion.STATUS_COMPLETED: Completion enters completed status.
    • SlimCompletion.STATUS_CANCELLED: Cancelled before the completion enters completed status.
  • handle (Promise<TSlimCompletionWaitHandle>): The wait handle (a promise object that resolves with this wait handle when it leaves SlimCompletion.STATUS_AWAIT status).
  • cancel (() => void): The cancellator function.

(Class) SlimCompletion

Slim completion source.

SlimCompletion.STATUS_{AWAIT, COMPLETED, CANCELLED}

Slim completion source wait handle status.

new SlimCompletion()

Construct a new object.

cp.wait([nonblock = false])

Wait for the completion enters completed status.

Parameter(s):

  • nonblock (Boolean): True if non-block mode is on.

Return value:

  • (?TSlimCompletionWaitHandle) The wait handle (NULL if non-block mode is on and the completion is not in completed status yet).
cp.complete()

Enter completed status.

SlimCompletion.WaitCondition(cond, [nonblock = false])

Wait for condition.

Parameter(s):

  • cond (ConditionalSynchronizer): The conditional synchronizer.
  • nonblock (Boolean): True if non-block mode is on.

Return value:

  • (?TSlimCompletionWaitHandle) The wait handle (NULL if non-block mode is on and the conditional synchronizer is not fullfilled yet).

(Module) Synchronize.Event

(Type) TSlimEventFlagsWaitHandle : Object

Slim event flags wait handle.

Properties:

  • status (Number): Current status:
    • SlimEventFlags.STATUS_AWAIT: Wait for specified condition satisfies.
    • SlimEventFlags.STATUS_SATISFIED: The wait condition has been satisfied.
    • SlimEventFlags.STATUS_CANCELLED: Cancelled before the wait condition satisfies.
  • value (Number): The flag value at the time that the wait condition satisfies.
  • handle (*Promise<TSlimEventFlagsWaitHandle>): The wait handle (a promise object that resolves with this wait handle when it leaves SlimEventFlags.STATUS_AWAIT status).
  • cancel (() => void): The cancellator function.

(Class) EventFlags

Event flags.

new EventFlags([initialValue = 0])

Construct a new object.

Exception(s):

  • EventFlags.ParameterError: The initial value is invalid.

Parameter(s):

  • initialValue (Number): (Optional) The initial flag value.
(Property) value (read/write)

Get/set current flag value.

Exception(s):

  • EventFlags.ParameterError: The new value is invalid.
evflags.pend(flags, opt, [cancellator])

Wait for a combination of conditions or events (i.e. bits) to be set (or cleared) in an event flag group.

Note(s):

  • The application can wait for any condition to be set or cleared, for all conditions to be set or cleared. If the events that the caller desires are not available, the caller is blocked until the desired conditions or events are satisfied or the cancellator was activated.

Exception(s):

  • EventFlags.ParameterError: One of following error occurred:
    • 'flags' is not an unsigned 32-bit integer.
    • 'opt' contains invalid option (or combination of options).
  • EventFlags.OperationCancelledError: The cancellator was activated.

Parameter(s):

  • flags (Number): A bit pattern indicating which bit(s) (i.e., flags) to check. The bits wanted are specified by setting the corresponding bits in flags. If the application wants to wait for bits 0 and 1 to be set, specify 0x03. The same applies if you'd want to wait for the same 2 bits to be cleared (you'd still specify which bits by passing 0x03).

  • opt (Number):

    • An integer that specifies whether all bits are to be set/cleared or any of the bits are to be set/cleared. Here are the options:
      • EventFlags.PEND_FLAG_CLR_ALL
      • EventFlags.PEND_FLAG_CLR_ANY
      • EventFlags.PEND_FLAG_SET_ALL
      • EventFlags.PEND_FLAG_SET_ANY
    • The caller may also specify whether the flags are consumed by "adding" EventFlags.PEND_FLAG_CONSUME to this parameter. For example, to wait for any flag in a group and then clear the flags that satisfy the condition, you would set this parameter to:
      • EventFlags.PEND_FLAG_SET_ALL + EventFlags.PEND_FLAG_CONSUME
  • cancellator (Synchronize.Conditional.ConditionalSynchronizer): The cancellator.

Return value:

  • (Promise<Number>) The promise object (resolves with an integer that flags that caused the promise object being resolved, rejects if error occurred).
evflags.post(flags, opt)

Set or clear event flag bits.

Note(s):

  • The bits set or cleared are specified in a bit mask (i.e., the flags parameter). The caller can set or clear bits that are already set or cleared.

Exception(s):

  • EventFlags.ParameterError: One of following error occurred:
    • 'flags' is not an unsigned 32-bit integer.
    • 'opt' contains invalid option (or combination of options).

Parameter(s):

  • flags (Number): An integer that specifies which bits to be set or cleared. If opt is EventFlags.POST_FLAG_SET, each bit that is set in flags will set the corresponding bit in the event flag group. For example to set bits 0, 4 and 5, you would set flags to 0x31 (note that bit 0 is the least significant bit). If opt is EventFlags.POST_FLAG_CLR, each bit that is set in flags will clear the corresponding bit in the event flag group. For example to clear bits 0, 4, and 5, you would specify flags as 0x31 (again, bit 0 is the least significant bit).
  • An integer that indicates whether the flags are set (EventFlags.POST_FLAG_SET) or cleared (EventFlags.POST_FLAG_CLR).

(Class) EventFlags.Error

Event flags error.

Extend(s):

  • Error

(Class) EventFlags.ParameterError

Event flags parameter error.

Extend(s):

  • EventFlags.Error

(Class) EventFlags.OperationCancelledError

Event flags operation cancelled error.

Extend(s):

  • EventFlags.Error

(Class) SlimEventFlags

Slim event flags.

SlimEventFlags.STATUS_{AWAIT, SATISFIED, CANCELLED}

Slim event flags wait handle status.

new SlimEventFlags([initialValue = 0x00000000])

Construct a new object.

Note(s):

  • The initial flag value shall be an unsigned 32-bit integer.
    • 0x00000000 would be used as the initial flag value if specified initial flag value is not an integer or is a negative integer.
    • 0xFFFFFFFF would be used as the initial flag value if specified initial flag value is greater than 0xFFFFFFFF.

Parameter(s):

  • initialValue (Number): The initial flag value.
sef.wait(onebits, [zerobits = 0x00000000], [nonblock = false])

Wait for specified condition satisfies.

Note(s):

  • The condition indicated by following formula is monitored:
    • ((flag & onebits) == onebits) && ((flag & zerobits) == 0)
  • Both "onebits" and "zerobits" parameters are assumed to be unsigned 32-bit integers. No additional parameter validity check would be performed on both parameters for performance reason. Behavior is undefined when any of both is not an unsigned 32-bit integer.

Parameter(s)

  • onebits (Number): An unsigned 32-bit integer that indicates which bits of the flag should be 1.
  • zerobits (Number): An unsigned 32-bit integer that indicates which bits of the flag should be 0.
  • nonblock (Boolean): True if non-block mode is on.

Return value:

  • (?TSlimEventFlagsWaitHandle) The wait handle (NULL if non-block mode is on and the condition is not satisfied yet).
sef.customWait(chk, [nonblock = false])

Wait for custom condition satisfies.

Parameter(s):

  • chk ((flag: Number) => Boolean): The custom condition satisfication checker function.
    • This function shall return true if the flag value satisfies the condition.
    • This function shall return false otherwise.
  • nonblock (Boolean): True if non-block mode is on.

Return value:

  • (?TSlimEventFlagsWaitHandle) The wait handle (NULL if non-block mode is on and the condition is not satisfied yet).
sef.current()

Get current flag value.

Return value:

  • (Number) The flag value.
sef.modify(orbits, [andbits = 0xFFFFFFFF], [xorbits = 0x00000000])

Modify the flag value.

Note(s):

  • New flag value is calculated according to following formula:
    • flag = (((flag | orbits) & andbits) ^ xorbits)
  • "orbits", "andbits" and "xorbits" parameters must be unsigned 32-bit integer. No additional parameter validity check would be performed on these parameters for performance reason. Behavior is undefined when any of these parameters is not an unsigned 32-bit integer.

Parameter(s):

  • orbits (Number): The ORing bits.
  • andbits (Number): The ANDing bits.
  • xorbits (Number): The XORing bits.
sef.assign(u32new)

Assign the flag value.

Note(s):

  • The new flag value must be an unsigned 32-bit integer. Behavior is undefined when the new flag value is not an unsigned 32-bit integer.

Parameter(s):

  • u32new (Number): The new flag value.

(Module) Synchronize.Lock

Introduction: This module implements asynchronous lock (mutex).

(Class) LockSynchronizer

Lock synchronizer.

Note(s):

  • All lock-acquire request would be queued an processed one-by-one.
  • The order of acquiring the lock depends on the order of lock-acquire operations.
  • The earlier the lock-acquire operation requests, the earlier the lock-acquire operation acquires the lock.
  • The implementation promises that the order of acquiring the lock is highly reliable and the behavior won't be changed in future releases of this library.
new LockSynchronizer()

Construct a new object.

lock.acquire([cancellator])

Acquire the lock.

Exception(s):

  • LockSynchronizer.OperationCancelledError: Raised when the cancellator was activated.

Parameter(s):

  • cancellator (Synchronize.Conditional.ConditionalSynchronizer): The cancellator.

Return value:

  • (Promise<Synchronize.Conditional.ConditionalSynchronizer>) The promise object (release synchronizer will be passed).

Example:

//  Tasks context.
let lock = new XRTLibAsync.Synchronize.Lock.LockSynchronizer();

async function RunTask(taskId) {
    //  Acquire the lock.
    let releaser = await lock.acquire();
    console.log("Task " + taskId.toString() + " acquired the lock.");

    //  Do something...
    await XRTLibAsync.Asynchronize.Timeout.CreateTimeoutPromise(1000 * Math.random());

    //  Release the lock.
    console.log("Task " + taskId.toString() + " released the lock.");
    releaser.fullfill();
}

//  Create 10 tasks.
for (let i = 1; i <= 10; ++i) {
    RunTask(i);
}

//  Output:
//    Task 1 acquired the lock.
//    Task 1 released the lock.
//    Task 2 acquired the lock.
//    ...
//    Task 10 released the lock.

(Class) LockSynchronizer.Error

Lock synchronizer error.

Extend(s):

  • Error

(Class) LockSynchronizer.OperationCancelledError

Lock synchronizer operation cancelled error.

Extend(s):

  • LockSynchronizer.Error

(Module) Synchronize.Notify (deprecated)

Introduction: This module implements a notification synchronizer.

Warning(s):

  • This module has been deprecated.
  • The existence of this module is ONLY for compatible. You shall NOT use any API of this module in new application.

(Class) NotificationSynchronizer<T>

Notification synchronizer.

new NotificationSynchronizer()

Construct a new object.

ns.register(cb)

Register a callback.

Parameter(s):

  • cb ((value: T) => void): The callback.
ns.unregister(cb)

Unregister a callback.

Parameter(s):

  • cb ((value: T) => void): The callback.
ns.notify(...args)

Notify all callbacks.

(Module) Synchronize.Poll

Introduction: This module implements a poll-based event waiter.

(Class) PollError

Poll error.

Extend(s):

  • Error

(Class) PollOperationCancelledError

Poll operation cancelled error.

Extend(s):

  • PollError

PollFor(detector, delayMin, delayMax, delayIncreaseRatio, [cancellator])

Poll for a customized condition to be fullfilled.

Parameter(s):

  • detector (()=>Boolean): The condition detector (return True when the condition was fullfilled).
  • delayMin (Number): The minimum detect interval (must larger than 0).
  • delayMax (Number): The maximum detect interval.
  • delayIncreaseRatio (Number): The increase ratio of the detect interval.
  • cancellator (Synchronize.Conditional.ConditionalSynchronizer): The cancellator.

Return value:

  • (Promise) The promise object (resolves when the condition fullfilled, rejects if the cancellator was activated).

PollForEx<T>(detector, resvData, delayMin, delayMax, delayIncreaseRatio, cancellator)

(Extend) Poll for a customized condition to be fullfilled.

Exception(s):

  • PollOperationCancelledError: Raised when the cancellator was activated.

Parameter(s):

  • detector (()=>Boolean): The condition detector (return True when the condition was fullfilled).
  • resvData (T): The data passed to Promise.resolve() method.
  • delayMin (Number): The minimum detect interval (must larger than 0).
  • delayMax (Number): The maximum detect interval.
  • delayIncreaseRatio (Number): The increase ratio of the detect interval.
  • cancellator (Synchronize.Conditional.ConditionalSynchronizer): The cancellator.

Return value:

  • (Promise<T>) The promise object (resolves when the condition fullfilled, rejects if the cancellator was activated).

(Module) Synchronize.Semaphore

Introduction: This module implements asynchronous semaphore.

(Class) SemaphoreSynchronizer

Semaphore synchronizer.

Note(s):

  • All P() operations would be queued an processed one-by-one.
  • The order of acquiring the semaphore depends on the order of P() operations.
  • The earlier the P() operation requests, the earlier the P() operation acquires the semaphore.
  • The implementation promises that the order of acquiring the semaphore is highly reliable and won't be changed in future releases of this library.
new SemaphoreSynchronizer(initialCount)

Construct a new object.

Parameter(s):

  • initialCount (Number): The initial value of the internal counter.
semaphore.wait([cancellator])

Do wait (P) operation.

Exception(s):

  • SemaphoreSynchronizer.OperationCancelledError: Raised when the cancellator was activated.

Parameter(s):

  • cancellator (Synchronize.Conditional.ConditionalSynchronizer): The cancellator.

Return value:

  • (Promise) The promise object (resolves if acquired successfully, rejects if error occurred).
semaphore.signal()

Do signal (V) operation.

semaphore.getCount()

Get the value of the counter.

Return value:

  • (Number) The value.
semaphore.isCanAcquireImmediately()

Get whether we can acquire the semaphore without waiting.

Return value:

  • (Boolean) True if so.
semaphore.isWaiting()

Get whether there is a P() operation waiting for signal now.

Return value:

  • (Boolean) True if so.

(Class) SlimSemaphoreSynchronizer

Slim semaphore synchronizer.

SlimSemaphoreSynchronizer.STATUS_{AWAIT, ENTERED, CANCELLED}

Slim semaphore synchronizer wait handle status.

new SlimSemaphoreSynchronizer([initialTokens = 0])

Construct a new object.

Note(s):

  • The initial token count must be a non-negative integer or Infinity.
    • If the initial token count is less than 0, it would be set to 0.
    • If the initial token count is NaN, it would be set to 0.
    • If the initial token count is a finite non-integer number, it would be floored to the nearest integer that is less than it.
    • If the initial token count is not a Number object, if would be set to 0.

Parameter(s):

  • initialTokens (Number): The initial token count.
ssem.wait([nonblock = false])

Wait for entering the semaphore.

Parameter(s):

  • nonblock (Boolean): True if non-block mode is on.

Return value:

  • (?TSlimSemaphoreWaitHandle) The wait handle (NULL if non-block mode is on and unable to enter the semaphore without blocking).
ssem.signal()

Release the semaphore.

ssem.forever()

Release the semaphore forever.

Note(s):

  • Release the semaphore forever means that all threads (coroutines) that are currently waiting for entering the semaphore would be granted to enter the semaphore. All future requests to enter the semaphore would also be granted to enter the semaphore immediately without blocking.