AsyncHandle
优质
小牛编辑
142浏览
2023-12-01
An AsyncHandle
provides a Promises/A+ compliant interface for an AsyncSequence that is currently (or was) iterating over its elements.
In addition to behaving as a promise, an AsyncHandle
provides the ability to AsyncHandle#cancel iteration (if cancelFn
is provided) and also offers convenient AsyncHandle#onComplete and AsyncHandle#onError methods to attach listeners for when iteration is complete or an error is thrown during iteration.
Signature
function AsyncHandle(cancelFn) { /*...*/ }
function AsyncHandle(cancelFn) { this.resolveListeners = []; this.rejectListeners = []; this.state = PENDING; this.cancelFn = cancelFn; }
Name | Type(s) | Description |
---|---|---|
cancelFn | Function | A function to cancel asynchronous iteration. This is passed in to support different cancellation mechanisms for different forms of asynchronous sequences (e.g., timeout-based sequences, sequences based on I/O, etc.). |
Examples
// Create a sequence of 100,000 random numbers, in chunks of 100. var sequence = Lazy.generate(Math.random) .chunk(100) .async() .take(1000); // Reduce-style operations -- i.e., operations that return a *value* (as // opposed to a *sequence*) -- return an AsyncHandle for async sequences. var handle = sequence.toArray(); handle.onComplete(function(array) { // Do something w/ 1,000-element array. }); // Since an AsyncHandle is a promise, you can also use it to create // subsequent promises using `then` (see the Promises/A+ spec for more // info). var flattened = handle.then(function(array) { return Lazy(array).flatten(); });