Methods
# (async, generator) asyncIterableWrap(iterable)
Wraps an iterable or async iterable into an iterable that is guaranted to be async.
Name | Type | Description |
---|---|---|
iterable |
Iterable | AsyncIterable | An iterable or async iterable object. |
- Source:
import { asyncIterableWrap } from 'modern-async'
// example sync generator
function* syncGenerator() {
for (let i = 0; i < 3; i += 1) {
yield i
}
}
const asyncIterable = asyncIterableWrap(syncGenerator())
for await (const el of asyncIterable) {
console.log(el)
}
// will print:
// 0
// 1
// 2
# (async) asyncRoot(fct, errorHandleropt)
Immediately calls an asynchronous function and redirects to an error handler if it throws an exception. The error handler is optional, the default one just outputs the error in the console.
This function is trivial but useful when you can't use top-level await for compatibility reasons.
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
fct |
function | An asynchronous function to call. |
||
errorHandler |
function |
<optional> |
null | A facultative error handler. This function will receive a single argument: the thrown exception. The default behavior is to output the exception in the console. |
- Source:
import { asyncRoot } from 'modern-async'
asyncRoot(async () => {
// any code using await
}, (e) => {
console.error("An error occured", e)
process.exit(-1)
})
# asyncWrap(fct) → {function}
Wraps a function call that may be synchronous in a function that
is guaranted to be async. This is a stricter version of calling a
function and wrapping its result using Promise.resolve()
as the new function also
handles the case where the original function throws an exception.
Name | Type | Description |
---|---|---|
fct |
function | The function to wrap. |
- Source:
The wrapped function.
- Type
- function
import { asyncWrap } from 'modern-async'
const myFunction = () => {
// any kind of function that may or may not return a promise
}
const asyncFct = asyncWrap(myFunction)
const promise = asyncFct()
console.log(promise instanceof Promise) // prints true
# (async) delay() → {Promise.<void>}
A function returning a promise that will be resolved in a later task of the event loop.
This function uses core-js' shim for setImmediate()
internally.
A promise that will be resolved on a later tick of the event loop.
- Type
- Promise.<void>
import { delay } from 'modern-async'
console.log('this executes in a tick of the event loop')
await delay()
console.log('this executes in another tick of the event loop')
# delayCancellable() → {Array}
A function returning a promise that will be resolved in a later tick of the event loop.
This function returns both a promise and cancel function in order to cancel the wait time if necessary. If cancelled, the promise will be rejected with a CancelledError.
This function uses core-js' shim for setImmediate()
internally.
- Source:
A tuple of two objects:
- The promise
- The cancel function. It will return a boolean that will be true if the promise was effectively cancelled, false otherwise.
- Type
- Array
import { delayCancellable, CancelledError } from 'modern-async'
const [promise, cancel] = delayCancellable()
cancel()
try {
await promise
} catch (e) {
console.log(e instanceof CancelledError) // prints true
}
# (async) every(iterable, iteratee) → {Promise.<boolean>}
Returns true
if all elements of an iterable pass a truth test and false
otherwise.
The iteratee will be run in parallel. If any truth test returns false
the promise is immediately resolved.
In case of exception in one of the iteratee calls the promise returned by this function will be rejected
with the exception. In the very specific case where a test returns false
and an already started task throws
an exception that exception will be plainly ignored.
Name | Type | Description |
---|---|---|
iterable |
Iterable | AsyncIterable | An iterable or async iterable object. |
iteratee |
function | A function that will be called with each member of the iterable. It will receive three arguments:
|
A promise that will be resolved to true
if all values pass the truth test and false
if a least one of them doesn't pass it. That promise will be rejected if one of the truth test throws
an exception.
- Type
- Promise.<boolean>
import { every, sleep } from 'modern-async'
const array = [1, 2, 3]
const result = await every(array, async (v) => {
// these calls will be performed in parallel
await sleep(10) // waits 10ms
return v > 0
})
console.log(result) // prints true
// total processing time should be ~ 10ms
# (async) everyLimit(iterable, iteratee, queueOrConcurrency) → {Promise.<boolean>}
Returns true
if all elements of an iterable pass a truth test and false
otherwise.
The calls to iteratee
will be performed in a queue to limit the concurrency of these calls.
If any truth test returns false
the promise is immediately resolved.
Whenever a test returns false
, all the remaining tasks will be cancelled as long
as they didn't started already. In case of exception in one of the iteratee calls the promise
returned by this function will be rejected with the exception and the remaining pending
tasks will also be cancelled. In the very specific case where a test returns false
and an
already started task throws an exception that exception will be plainly ignored.
Name | Type | Description |
---|---|---|
iterable |
Iterable | AsyncIterable | An iterable or async iterable object. |
iteratee |
function | A function that will be called with each member of the iterable. It will receive three arguments:
|
queueOrConcurrency |
Queue | number | If a queue is specified it will be used to schedule the calls to
|
- Source:
A promise that will be resolved to true
if all values pass the truth test and false
if a least one of them doesn't pass it. That promise will be rejected if one of the truth test throws
an exception.
- Type
- Promise.<boolean>
import { everyLimit, sleep } from 'modern-async'
const array = [1, 2, 3]
const result = await everyLimit(array, async (v) => {
// these calls will be performed in parallel with a maximum of 2
// concurrent calls
await sleep(10) // waits 10ms
return v > 0
}, 2)
console.log(result) // prints true
// total processing time should be ~ 20ms
# (async) everySeries(iterable, iteratee) → {Promise.<boolean>}
Returns true
if all elements of an iterable pass a truth test and false
otherwise.
The iteratee will be run sequentially. If any truth test returns false
the promise is
immediately resolved.
In case of exception in one of the iteratee calls the promise returned by this function will be rejected with the exception and the remaining pending tasks will be cancelled.
Name | Type | Description |
---|---|---|
iterable |
Iterable | AsyncIterable | An iterable or async iterable object. |
iteratee |
function | A function that will be called with each member of the iterable. It will receive three arguments:
|
- Source:
A promise that will be resolved to true
if all values pass the truth test and false
if a least one of them doesn't pass it. That promise will be rejected if one of the truth test throws
an exception.
- Type
- Promise.<boolean>
import { everySeries, sleep } from 'modern-async'
const array = [1, 2, 3]
const result = await everySeries(array, async (v) => {
// these calls will be performed sequentially
await sleep(10) // waits 10ms
return v > 0
})
console.log(result) // prints true
// total processing time should be ~ 30ms
# (async) filter(iterable, iteratee) → {Promise.<Array.<any>>}
Returns an array of all the values in iterable
which pass an asynchronous truth test.
The calls to iteratee
will perform in parallel. The results will be in the same order than in iterable
.
If any of the calls to iteratee
throws an exception the returned promise will be rejected.
Name | Type | Description |
---|---|---|
iterable |
Iterable | AsyncIterable | An iterable or async iterable object. |
iteratee |
function | A function that will be called with each member of
|
- Source:
A promise that will be resolved with an array containing all the values that passed
the truth test. This promise will be rejected if any of the iteratee
calls throws an exception.
- Type
- Promise.<Array.<any>>
import { filter, sleep } from 'modern-async'
const array = [1, 2, 3]
const result = await filter(array, async (v) => {
// these calls will be performed in parallel
await sleep(10) // waits 10ms
return v % 2 === 1
})
console.log(result) // prints [1, 3]
// total processing time should be ~ 10ms
})
# (async, generator) filterGenerator(iterable, iteratee, queueOrConcurrencyopt, orderedopt)
Produces a an async iterator that will return each value or iterable
which pass an asynchronous truth test.
The iterator will perform the calls to iteratee
in a queue to limit the concurrency of
these calls. The iterator will consume values from iterable
only if slots are available in the
queue.
If the returned iterator is not fully consumed it will stop consuming new values from iterable
and scheduling
new calls to iteratee
in the queue, but already scheduled tasks will still be executed.
If iterable
or any of the calls to iteratee
throws an exception all pending tasks will be cancelled and the
returned async iterator will throw that exception.
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
iterable |
Iterable | AsyncIterable | An iterable or async iterable object. |
||
iteratee |
function | A function that will be called with each member of the iterable. It will receive three arguments:
|
||
queueOrConcurrency |
Queue | number |
<optional> |
1 | If a queue is specified it will be used to schedule the calls to
|
ordered |
boolean |
<optional> |
true | If true the results will be yielded in the same order as in the source iterable, regardless of which calls to iteratee returned first. If false the the results will be yielded as soon as a call to iteratee returned. |
- Source:
import {filterGenerator, sleep} from 'modern-async'
const iterator = function * () {
for (let i = 0; i < 10000; i += 1) {
yield i
}
}
const filterIterator = filterGenerator(iterator(), async (v) => {
await sleep(1000)
return v % 3 === 0
})
for await (const el of filterIterator) {
console.log(el)
}
// will print "0", "3", "6", etc... Only one number will be printed every 3 seconds.
# (async) filterLimit(iterable, iteratee, queueOrConcurrency) → {Promise.<Array.<any>>}
Returns an array of all the values in iterable
which pass an asynchronous truth test.
The calls to iteratee
will be performed in a queue to limit the concurrency of these calls.
The results will be in the same order than in iterable
.
If any of the calls to iteratee
throws an exception the returned promise will be rejected and the remaining
pending tasks will be cancelled.
Name | Type | Description |
---|---|---|
iterable |
Iterable | AsyncIterable | An iterable or async iterable object. |
iteratee |
function | A function that will be called with each member of
|
queueOrConcurrency |
Queue | number | If a queue is specified it will be used to schedule the calls to
|
- Source:
A promise that will be resolved with an array containing all the values that passed
the truth test. This promise will be rejected if any of the iteratee
calls throws an exception.
- Type
- Promise.<Array.<any>>
import { filterLimit, sleep } from 'modern-async'
const array = [1, 2, 3]
const result = await filterLimit(array, async (v) => {
// these calls will be performed in parallel with a maximum of 2
// concurrent calls
await sleep(10) // waits 10ms
return v % 2 === 1
}, 2)
console.log(result) // prints [1, 3]
// total processing time should be ~ 20ms
# (async) filterSeries(iterable, iteratee) → {Promise.<Array.<any>>}
Returns an array of all the values in iterable
which pass an asynchronous truth test.
The calls to iteratee
will perform sequentially. The results will be in the same order than in iterable
.
If any of the calls to iteratee
throws an exception the returned promise will be rejected and the remaining
pending tasks will be cancelled.
Name | Type | Description |
---|---|---|
iterable |
Iterable | AsyncIterable | An iterable or async iterable object. |
iteratee |
function | A function that will be called with each member of the iterable. It will receive three arguments:
|
- Source:
A promise that will be resolved with an array containing all the values that passed
the truth test. This promise will be rejected if any of the iteratee
calls throws an exception.
- Type
- Promise.<Array.<any>>
import { filterSeries, sleep } from 'modern-async'
const array = [1, 2, 3]
const result = await filterSeries(array, async (v) => {
// these calls will be performed sequentially
await sleep(10) // waits 10ms
return v % 2 === 1
})
console.log(result) // prints [1, 3]
// total processing time should be ~ 30ms
})
# (async) find(iterable, iteratee, orderedopt) → {Promise.<(any|undefined)>}
Returns the first element of an iterable that passes an asynchronous truth test.
The calls to iteratee
will run in parallel.
In case of exception in one of the iteratee
calls the promise returned by this function will be
rejected with the exception. In the very specific case where a result is found and an
already started task throws an exception that exception will be plainly ignored.
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
iterable |
Iterable | AsyncIterable | An iterable or async iterable object. |
||
iteratee |
function | A function that will be called with each member of the iterable. It will receive three arguments:
|
||
ordered |
boolean |
<optional> |
false | If true this function will return on the first element in the iterable
order for which |
A promise that will be resolved with the first found value or rejected if one of the
iteratee
calls throws an exception before finding a value. If no value is found it will return undefined
.
- Type
- Promise.<(any|undefined)>
import { find, sleep } from 'modern-async'
const array = [1, 2, 3]
const result = await find(array, async (v) => {
// these calls will be performed in parallel
await sleep(Math.random() * 10) // waits a random amount of time between 0ms and 10ms
return v % 2 === 1
})
console.log(result) // prints 1
# (async) findIndex(iterable, iteratee, orderedopt) → {Promise.<number>}
Returns the index of the first element of an iterable that passes an asynchronous truth test.
The calls to iteratee
will run in parallel.
In case of exception in one of the iteratee
calls the promise returned by this function will be
rejected with the exception. In the very specific case where a result is found and an
already started task throws an exception that exception will be plainly ignored.
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
iterable |
Iterable | AsyncIterable | An iterable or async iterable object. |
||
iteratee |
function | A function that will be called with each member of the iterable. It will receive three arguments:
|
||
ordered |
boolean |
<optional> |
false | If true this function will return on the first element in the iterable
order for which |
- Source:
A promise that will be resolved with the index of the first found value or rejected if one of the
iteratee
calls throws an exception before finding a value. If no value is found it will return -1
.
- Type
- Promise.<number>
import { findIndex, sleep } from 'modern-async'
const array = [1, 2, 3]
const result = await findIndex(array, async (v) => {
// these calls will be performed in parallel
await sleep(Math.random() * 10) // waits a random amount of time between 0ms and 10ms
return v % 2 === 1
})
console.log(result) // prints 0
# (async) findIndexLimit(iterable, iteratee, queueOrConcurrency, orderedopt) → {Promise.<number>}
Returns the index of the first element of an iterable that passes an asynchronous truth test.
The calls to iteratee
will be performed in a queue to limit the concurrency of these calls.
Whenever a result is found, all the remaining tasks will be cancelled as long as they didn't started already. In case of exception in one of the iteratee calls the promise returned by this function will be rejected with the exception and the remaining pending tasks will also be cancelled. In the very specific case where a result is found and an already started task throws an exception that exception will be plainly ignored.
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
iterable |
Iterable | AsyncIterable | An iterable or async iterable object. |
||
iteratee |
function | A function that will be called with each member of the iterable. It will receive three arguments:
|
||
queueOrConcurrency |
Queue | number | If a queue is specified it will be used to schedule the calls to
|
||
ordered |
boolean |
<optional> |
false | If true this function will return on the first element in the iterable
order for which |
- Source:
A promise that will be resolved with the index of the first found value or rejected if one of the
iteratee
calls throws an exception before finding a value. If no value is found it will return -1
.
- Type
- Promise.<number>
import { findIndexLimit, sleep } from 'modern-async'
const array = [1, 2, 3, 4, 5]
const result = await findIndexLimit(array, async (v) => {
// these calls will be performed in parallel with a maximum of 3
// concurrent calls
await sleep(Math.random() * 10) // waits a random amount of time between 0ms and 10ms
return v % 2 === 1
}, 3)
console.log(result) // prints 0
# (async) findIndexSeries(iterable, iteratee) → {Promise.<number>}
Returns the index of the first element of an iterable that passes an asynchronous truth test.
The calls to iteratee
will run sequentially.
In case of exception in one of the iteratee
calls the promise returned by this function will be
rejected with the exception and the remaining pending tasks will be cancelled.
Name | Type | Description |
---|---|---|
iterable |
Iterable | AsyncIterable | An iterable or async iterable object. |
iteratee |
function | A function that will be called with each member of the iterable. It will receive three arguments:
|
- Source:
A promise that will be resolved with the index of the first found value or rejected if one of the
iteratee
calls throws an exception before finding a value. If no value is found it will return -1
.
- Type
- Promise.<number>
import { findIndexSeries, sleep } from 'modern-async'
const array = [1, 2, 3]
const result = await findIndexSeries(array, async (v) => {
// these calls will be performed sequentially
await sleep(Math.random() * 10) // waits a random amount of time between 0ms and 10ms
return v % 2 === 1
})
console.log(result) // prints 0
# (async) findLimit(iterable, iteratee, queueOrConcurrency, orderedopt) → {Promise.<(any|undefined)>}
Returns the first element of an iterable that passes an asynchronous truth test.
The calls to iteratee
will be performed in a queue to limit the concurrency of these calls.
Whenever a result is found, all the remaining tasks will be cancelled as long
as they didn't started already. In case of exception in one of the iteratee
calls the promise
returned by this function will be rejected with the exception and the remaining pending
tasks will also be cancelled. In the very specific case where a result is found and an
already started task throws an exception that exception will be plainly ignored.
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
iterable |
Iterable | AsyncIterable | An iterable or async iterable object. |
||
iteratee |
function | A function that will be called with each member of the iterable. It will receive three arguments:
|
||
queueOrConcurrency |
Queue | number | If a queue is specified it will be used to schedule the calls to
|
||
ordered |
boolean |
<optional> |
false | If true this function will return on the first element in the iterable
order for which |
- Source:
A promise that will be resolved with the first found value or rejected if one of the
iteratee
calls throws an exception before finding a value. If no value is found it will return undefined
.
- Type
- Promise.<(any|undefined)>
import { findLimit, sleep } from 'modern-async'
const array = [1, 2, 3, 4, 5]
const result = await findLimit(array, async (v) => {
// these calls will be performed in parallel with a maximum of 3
// concurrent calls
await sleep(Math.random() * 10) // waits a random amount of time between 0ms and 10ms
return v % 2 === 1
}, 3)
console.log(result) // prints 1
# (async) findSeries(iterable, iteratee) → {Promise.<(any|undefined)>}
Returns the first element of an iterable that passes an asynchronous truth test.
The calls to iteratee
will run sequentially.
In case of exception in one of the iteratee
calls the promise returned by this function will be
rejected with the exception and the remaining pending tasks will be cancelled.
Name | Type | Description |
---|---|---|
iterable |
Iterable | AsyncIterable | An iterable or async iterable object. |
iteratee |
function | A function that will be called with each member of the iterable. It will receive three arguments:
|
- Source:
A promise that will be resolved with the first found value or rejected if one of the
iteratee
calls throws an exception before finding a value. If no value is found it will return undefined
.
- Type
- Promise.<(any|undefined)>
import { findSeries, sleep } from 'modern-async'
const array = [1, 2, 3]
const result = await findSeries(array, async (v) => {
// these calls will be performed sequentially
await sleep(Math.random() * 10) // waits a random amount of time between 0ms and 10ms
return v % 2 === 1
})
console.log(result) // prints 1
# (async) forEach(iterable, iteratee) → {Promise}
Calls a function on each element of iterable.
Multiple calls to iteratee
will be performed in parallel.
If any of the calls to iteratee throws an exception the returned promise will be rejected.
Name | Type | Description |
---|---|---|
iterable |
Iterable | AsyncIterable | An iterable or async iterable object. |
iteratee |
function | A function that will be called with each member of the iterable. It will receive three arguments:
|
- Source:
A promise that will be resolved when all the calls to iteratee
have been done.
This promise will be rejected if any call to iteratee
throws an exception.
- Type
- Promise
import { forEach, sleep } from 'modern-async'
const array = [1, 2, 3]
await forEach(array, async (v) => {
// these calls will be performed in parallel
await sleep(Math.random() * 10) // waits a random amount of time between 0ms and 10ms
console.log(v)
})
// prints 1, 2 and 3 in a random order
})
# (async) forEachLimit(iterable, iteratee, queueOrConcurrency) → {Promise}
Calls a function on each element of iterable.
The calls to iteratee
will be performed in a queue to limit the concurrency of these calls.
If any of the calls to iteratee throws an exception the returned promise will be rejected and the remaining pending tasks will be cancelled.
Name | Type | Description |
---|---|---|
iterable |
Iterable | AsyncIterable | An iterable or async iterable object. |
iteratee |
function | A function that will be called with each member of the iterable. It will receive three arguments:
|
queueOrConcurrency |
Queue | number | If a queue is specified it will be used to schedule the calls to
|
- Source:
A promise that will be resolved when all the calls to iteratee
have been done.
This promise will be rejected if any call to iteratee
throws an exception.
- Type
- Promise
import { forEachLimit, sleep } from 'modern-async'
const array = [1, 2, 3]
await forEachLimit(array, async (v) => {
// these calls will be performed in parallel with a maximum of 2
// concurrent calls
await sleep(Math.random() * 10) // waits a random amount of time between 0ms and 10ms
console.log(v)
}, 2)
// prints 1, 2 and 3 in a random order (it will always print 1 or 2 before printing 3 due to
// the concurrency limit and the internal scheduling order)
# (async) forEachSeries(iterable, iteratee) → {Promise}
Calls a function on each element of iterable.
Multiple calls to iteratee
will be performed sequentially.
If any of the calls to iteratee throws an exception the returned promise will be rejected and the remaining pending tasks will be cancelled.
Name | Type | Description |
---|---|---|
iterable |
Iterable | AsyncIterable | An iterable or async iterable object. |
iteratee |
function | A function that will be called with each member of the iterable. It will receive three arguments:
|
- Source:
A promise that will be resolved when all the calls to iteratee
have been done.
This promise will be rejected if any call to iteratee
throws an exception.
- Type
- Promise
import { forEachSeries, sleep } from 'modern-async'
const array = [1, 2, 3]
await forEachSeries(array, async (v) => {
// these calls will be performed sequentially
await sleep(Math.random() * 10) // waits a random amount of time between 0ms and 10ms
console.log(v)
})
// prints 1, 2 and 3 in that exact order
# (async) map(iterable, iteratee) → {Promise.<Array.<any>>}
Produces a new collection of values by mapping each value in iterable
through the iteratee
function.
Multiple calls to iteratee
will be performed in parallel.
If any of the calls to iteratee throws an exception the returned promise will be rejected.
Name | Type | Description |
---|---|---|
iterable |
Iterable | AsyncIterable | An iterable or async iterable object. |
iteratee |
function | A function that will be called with each member of the iterable. It will receive three arguments:
|
A promise that will be resolved with an array containing all the mapped value,
or will be rejected if any of the calls to iteratee
throws an exception.
- Type
- Promise.<Array.<any>>
import { map, sleep } from 'modern-async'
const array = [1, 2, 3]
const result = await map(array, async (v) => {
// these calls will be performed in parallel
await sleep(10) // waits 10ms
return v * 2
})
console.log(result) // prints [2, 4, 6]
// total processing time should be ~ 10ms
# (async, generator) mapGenerator(iterable, iteratee, queueOrConcurrencyopt, orderedopt)
Produces a an async iterator that will return each value or iterable
after having processed them through
the iteratee
function.
The iterator will perform the calls to iteratee
in a queue to limit the concurrency of
these calls. The iterator will consume values from iterable
only if slots are available in the
queue.
If the returned iterator is not fully consumed it will stop consuming new values from iterable
and scheduling
new calls to iteratee
in the queue, but already scheduled tasks will still be executed.
If iterable
or any of the calls to iteratee
throws an exception all pending tasks will be cancelled and the
returned async iterator will throw that exception.
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
iterable |
Iterable | AsyncIterable | An iterable or async iterable object. |
||
iteratee |
function | A function that will be called with each member of the iterable. It will receive three arguments:
|
||
queueOrConcurrency |
Queue | number |
<optional> |
1 | If a queue is specified it will be used to schedule the calls to
|
ordered |
boolean |
<optional> |
true | If true the results will be yielded in the same order as in the source iterable, regardless of which calls to iteratee returned first. If false the the results will be yielded as soon as a call to iteratee returned. |
- Source:
import {mapGenerator, sleep} from 'modern-async'
const iterator = function * () {
for (let i = 0; i < 10000; i += 1) {
yield i
}
}
const mapIterator = mapGenerator(iterator(), async (v) => {
await sleep(1000)
return v * 2
})
for await (const el of mapIterator) {
console.log(el)
}
// Will print "0", "2", "4", etc... Only one number will be printed per second.
// Numbers from `iterator` will be consumed progressively
# (async) mapLimit(iterable, iteratee, queueOrConcurrency) → {Promise.<Array.<any>>}
Produces a new collection of values by mapping each value in iterable
through the iteratee
function.
The calls to iteratee
will be performed in a queue to limit the concurrency of these calls.
If any of the calls to iteratee throws an exception the returned promise will be rejected and the remaining pending tasks will be cancelled.
Name | Type | Description |
---|---|---|
iterable |
Iterable | AsyncIterable | An iterable or async iterable object. |
iteratee |
function | A function that will be called with each member of the iterable. It will receive three arguments:
|
queueOrConcurrency |
Queue | number | If a queue is specified it will be used to schedule the calls to
|
- Source:
A promise that will be resolved with an array containing all the mapped value,
or will be rejected if any of the calls to iteratee
throws an exception.
- Type
- Promise.<Array.<any>>
import { mapLimit, sleep } from 'modern-async'
const array = [1, 2, 3]
const result = await mapLimit(array, async (v) => {
// these calls will be performed in parallel with a maximum of 2
// concurrent calls
await sleep(10) // waits 10ms
return v * 2
}, 2)
console.log(result) // prints [2, 4, 6]
// total processing time should be ~ 20ms
# (async) mapSeries(iterable, iteratee) → {Promise.<Array.<any>>}
Produces a new collection of values by mapping each value in iterable
through the iteratee
function.
Multiple calls to iteratee
will be performed sequentially.
If any of the calls to iteratee throws an exception the returned promise will be rejected and the remaining pending tasks will be cancelled.
Name | Type | Description |
---|---|---|
iterable |
Iterable | AsyncIterable | An iterable or async iterable object. |
iteratee |
function | A function that will be called with each member of the iterable. It will receive three arguments:
|
- Source:
A promise that will be resolved with an array containing all the mapped value,
or will be rejected if any of the calls to iteratee
throws an exception.
- Type
- Promise.<Array.<any>>
import { mapSeries, sleep } from 'modern-async'
const array = [1, 2, 3]
const result = await mapSeries(array, async (v) => {
// these calls will be performed sequentially
await sleep(10) // waits 10ms
return v * 2
}, 2)
console.log(result) // prints [2, 4, 6]
// total processing time should be ~ 30ms
# queueMicrotask(fct)
An alternative to standard queueMicrotask()
function.
This is just of mirror of core-js' implementation for compatibility.
Name | Type | Description |
---|---|---|
fct |
function | The function to call in a microtask. |
- Source:
import { queueMicrotask } from 'modern-async'
queueMicrotask(() => {
console.log('this resolves in a micro task')
})
# (async) reduce(iterable, reducer, initialopt) → {Promise}
Performs a reduce operation as defined in the Array.reduce()
method but using an asynchronous
function as reducer. The reducer will be called sequentially.
Name | Type | Attributes | Description |
---|---|---|---|
iterable |
Iterable | AsyncIterable | An iterable or async iterable object. |
|
reducer |
function | The reducer function. It will be called with four arguments:
|
|
initial |
any |
<optional> |
The initial value that will be used as accumulator in the first call to
|
- Source:
A promise that will be resolved with the result of the reduce operation,
or rejected if any of the calls to reducer
throws an exception.
- Type
- Promise
import { reduce, sleep } from 'modern-async'
const array = [1, 2, 3]
const result = await reduce(array, async (v, p) => {
// these calls will be performed sequentially
await sleep(10) // waits 10ms
return v + p
})
console.log(result) // prints 6
// total processing time should be ~ 20ms
# (async) reduceRight(iterable, reducer, initialopt) → {Promise}
Performs a reduce operation as defined in the Array.reduceRight()
method but using an asynchronous
function as reducer. The reducer will be called sequentially.
Name | Type | Attributes | Description |
---|---|---|---|
iterable |
Iterable | AsyncIterable | An iterable object. |
|
reducer |
function | The reducer function. It will be called with four arguments:
|
|
initial |
any |
<optional> |
The initial value that will be used as accumulator in the first call to
reducer. If omitted the first element of |
- Source:
A promise that will be resolved with the result of the reduce operation,
or rejected if any of the calls to reducer
throws an exception.
- Type
- Promise
import { reduceRight, sleep } from 'modern-async'
const array = [1, 2, 3]
const result = await reduceRight(array, async (v, p) => {
// these calls will be performed sequentially
await sleep(10) // waits 10ms
return v + p
})
console.log(result) // prints 6
// total processing time should be ~ 20ms
# (async) sleep(amount) → {Promise.<void>}
Waits a given amount of time.
This function uses setTimeout()
internally and has the same behavior, notably that it could resolve
after the asked time (depending on other tasks running in the event loop) or a few milliseconds before.
Name | Type | Description |
---|---|---|
amount |
number | An amount of time in milliseconds |
A promise that will be resolved after the given amount of time has passed.
- Type
- Promise.<void>
import { sleep } from 'modern-async'
await sleep(100) // will wait 100ms
// another example that doesn't block on the sleep call
// it's functionally identical to using setTimout but with a promise syntax
import { sleep } from 'modern-async'
sleep(10).then(() => {
console.log('hello')
})
// will print 'hello' after 10ms
# sleepCancellable(amount) → {Array}
Waits a given amount of time. This function returns both a promise and cancel function in
order to cancel the wait time if necessary. If cancelled, the promise will be rejected
with a CancelledError
.
This function uses setTimeout()
internally and has the same behavior, notably that it could resolve
after the asked time (depending on other tasks running in the event loop) or a few milliseconds before.
Name | Type | Description |
---|---|---|
amount |
number | An amount of time in milliseconds |
- Source:
A tuple of two objects:
promise
: The promisecancel
: The cancel function. It will return a boolean that will betrue
if the promise was effectively cancelled,false
otherwise.
- Type
- Array
import { sleepCancellable } from 'modern-async'
const [promise, cancel] = sleepCancellable(100) // schedule to resolve the promise after 100ms
cancel()
try {
await promise
} catch (e) {
console.log(e.name) // prints CancelledError
}
# (async) sleepPrecise(amount) → {Promise.<void>}
Waits a given amount of time.
This function is similar to sleep()
except it ensures that the amount of time measured
using the Date
object is always greater than or equal the asked amount of time.
This function can imply additional delay that can be bad for performances. As such it is
recommended to only use it in unit tests or very specific cases. Most applications should
be adapted to work with the usual setTimout()
inconsistencies even if it can trigger some
milliseconds before the asked delay.
Name | Type | Description |
---|---|---|
amount |
number | An amount of time in milliseconds |
- Source:
A promise that will be resolved after the given amount of time has passed.
- Type
- Promise.<void>
import { sleepPrecise } from 'modern-async'
await sleepPrecise(100) // will wait 100ms
# sleepPreciseCancellable(amount) → {Array}
Waits a given amount of time.
This function returns both a promise and cancel function in order to cancel the
wait time if necessary. If cancelled, the promise will be rejected with a CancelledError
.
This function is similar to sleep()
except it ensures that the amount of time measured
using the Date
object is always greater than or equal the asked amount of time.
This function can imply additional delay that can be bad for performances. As such it is
recommended to only use it in unit tests or very specific cases. Most applications should
be adapted to work with the usual setTimout()
inconsistencies even if it can trigger some
milliseconds before the asked delay.
Name | Type | Description |
---|---|---|
amount |
number | An amount of time in milliseconds |
- Source:
A tuple of two objects:
promise
: The promisecancel
: The cancel function. It will return a boolean that will betrue
if the promise was effectively cancelled,false
otherwise.
- Type
- Array
import { sleepPreciseCancellable } from 'modern-async'
const [promise, cancel] = sleepPreciseCancellable(100) // schedule to resolve the promise after 100ms
cancel()
try {
await promise
} catch (e) {
console.log(e.name) // prints CancelledError
}
# (async) some(iterable, iteratee) → {Promise.<boolean>}
Returns true
if at least one element of an iterable pass a truth test and false
otherwise.
The calls to iteratee
will run in parallel. If any truth test returns true
the promise is immediately resolved.
In case of exception in one of the iteratee
calls the promise returned by this function will be rejected
with the exception. In the very specific case where a test returns true
and an already started task throws
an exception that exception will be plainly ignored.
Name | Type | Description |
---|---|---|
iterable |
Iterable | AsyncIterable | An iterable or async iterable object. |
iteratee |
function | A function that will be called with each member of the iterable. It will receive three arguments:
|
A promise that will be resolved to true
if at least one value pass the truth test and false
if none of them do. That promise will be rejected if one of the truth test throws an exception.
- Type
- Promise.<boolean>
import { some, sleep } from 'modern-async'
const array = [1, 2, 3]
const result = await some(array, async (v) => {
// these calls will be performed in parallel
await sleep(10) // waits 10ms
return v % 2 === 0
})
console.log(result) // prints true
// total processing time should be ~ 10ms
# (async) someLimit(iterable, iteratee, queueOrConcurrency) → {Promise.<boolean>}
Returns true
if at least one element of an iterable pass a truth test and false
otherwise.
The calls to iteratee
will be performed in a queue to limit the concurrency of these calls. If any
truth test returns true
the promise is immediately resolved.
Whenever a test returns true
, all the remaining tasks will be cancelled as long
as they didn't started already. In case of exception in one of the iteratee
calls the promise
returned by this function will be rejected with the exception and the remaining pending
tasks will also be cancelled. In the very specific case where a test returns true
and an
already started task throws an exception that exception will be plainly ignored.
Name | Type | Description |
---|---|---|
iterable |
Iterable | AsyncIterable | An iterable or async iterable object. |
iteratee |
function | A function that will be called with each member of the iterable. It will receive three arguments:
|
queueOrConcurrency |
Queue | number | If a queue is specified it will be used to schedule the calls to
|
- Source:
A promise that will be resolved to true
if at least one value pass the truth test and false
if none of them do. That promise will be rejected if one of the truth test throws an exception.
- Type
- Promise.<boolean>
import { someLimit, sleep } from 'modern-async'
const array = [1, 2, 3]
const result = await someLimit(array, async (v) => {
// these calls will be performed in parallel with a maximum of 2
// concurrent calls
await sleep(10) // waits 10ms
return v % 2 === 0
}, 2)
console.log(result) // prints true
// total processing time should be ~ 10ms
# (async) someSeries(iterable, iteratee) → {Promise.<boolean>}
Returns true
if all elements of an iterable pass a truth test and false
otherwise.
The calls to iteratee
will run sequentially. If any truth test returns true
the promise is
immediately resolved.
In case of exception in one of the iteratee calls the promise returned by this function will be rejected with the exception and the remaining pending tasks will be cancelled.
Name | Type | Description |
---|---|---|
iterable |
Iterable | AsyncIterable | An iterable or async iterable object. |
iteratee |
function | A function that will be called with each member of the iterable. It will receive three arguments:
|
- Source:
A promise that will be resolved to true
if at least one value pass the truth test and false
if none of them do. That promise will be rejected if one of the truth test throws an exception.
- Type
- Promise.<boolean>
import { someSeries, sleep } from 'modern-async'
const array = [1, 2, 3]
const result = await someSeries(array, async (v) => {
// these calls will be performed sequentially
await sleep(10) // waits 10ms
return v % 2 === 0
})
console.log(result) // prints true
// total processing time should be ~ 20ms
# (async) timeout(fct, amount) → {Promise}
Wraps a call to an asynchronous function to add a timer on it. If the delay is exceeded
the returned promise will be rejected with a TimeoutError
.
This function uses setTimeout()
internally and has the same behavior, notably that it could reject
after the asked time (depending on other tasks running in the event loop) or a few milliseconds before.
Name | Type | Description |
---|---|---|
fct |
function | An asynchronous function that will be called immediately without arguments. |
amount |
number | An amount of time in milliseconds |
- Source:
A promise that will be resolved or rejected according to the result of the call
to fct
. If amount
milliseconds pass before the call to fct
returns or rejects, this promise will
be rejected with a TimeoutError
.
- Type
- Promise
import { timeout, sleep } from 'modern-async'
// the following statement will perform successfully because
// the function will return before the delay
await timeout(async () => {
await sleep(10)
}, 100)
try {
// the following statement will throw after 10ms
await timeout(async () => {
await sleep(100)
}, 10)
} catch (e) {
console.log(e.name) // prints TimeoutError
}
# (async) timeoutPrecise(fct, amount) → {Promise}
Wraps a call to an asynchronous function to add a timer on it. If the delay is exceeded
the returned promise will be rejected with a TimeoutError
.
This function is similar to timeout()
except it ensures that the amount of time measured
using the Date
object is always greater than or equal the asked amount of time.
This function can imply additional delay that can be bad for performances. As such it is
recommended to only use it in unit tests or very specific cases. Most applications should
be adapted to work with the usual setTimout()
inconsistencies even if it can trigger some
milliseconds before the asked delay.
Name | Type | Description |
---|---|---|
fct |
function | An asynchronous function that will be called immediately without arguments. |
amount |
number | An amount of time in milliseconds |
- Source:
A promise that will be resolved or rejected according to the result of the call
to fct
. If amount
milliseconds pass before the call to fct
returns or rejects, this promise will
be rejected with a TimeoutError
.
- Type
- Promise
import { timeoutPrecise, sleep } from 'modern-async'
// the following statement will perform successfully because
// the function will return before the delay
await timeoutPrecise(async () => {
await sleep(10)
}, 100)
try {
// the following statement will throw after 10ms
await timeoutPrecise(async () => {
await sleep(100)
}, 10)
} catch (e) {
console.log(e.name) // prints TimeoutError
}
# (async) toArray(iterable) → {Promise.<Array.<any>>}
Fully consumes an iteratable or async iterable an returns an array with all the elements it contained.
Name | Type | Description |
---|---|---|
iterable |
Iterable | AsyncIterable | An iterator or async iterator. |
- Source:
An array.
- Type
- Promise.<Array.<any>>
import { toArray, sleep } from 'modern-async'
// example async generator
async function* asyncGenerator() {
for (let i = 0; i < 3; i += 1) {
await sleep(10)
yield i
}
}
console.log(await toArray(asyncGenerator()))
// prints [0, 1, 2]