Global

Methods

# (async) asyncRoot(fct, errorHandler)

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 in the context of node.js when you would like to use await in the root scope. It is also used in most examples provided for this library.

Parameters:
Name Type Default Description
fct function

An asynchronous function to call.

errorHandler function null

(Optional) 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.

Example
import { asyncRoot } from 'modern-async'

// or

const { asyncRoot } = require('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.

Parameters:
Name Type Description
fct function

The function to wrap.

Returns:

The wrapped function.

Type
function
Example
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}

A function returning a promise that will be resolved in a later tick of the event loop.

This function simply uses setTimeout() internally as it's the most portable solution.

Source:
Returns:

A promise that will be resolved on a later tick of the event loop.

Type
Promise
Example
import { delay, asyncRoot } from 'modern-async'

asyncRoot(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 simply uses setTimeout() internally as it's the most portable solution.

Returns:

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
Example
import { delayCancellable, asyncRoot, CancelledError } from 'modern-async'

asyncRoot(async () => {
  const [promise, cancel] = delayCancellable()
  cancel()
  try {
    await promise
  } catch (e) {
    console.log(e instanceof CancelledError) // prints true
  }
})

# (async) every(iterable, iteratee) → {Promise}

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.

Parameters:
Name Type Description
iterable Iterable

An iterable object.

iteratee function

A function that will be called with each member of the iterable. It will receive three arguments:

  • value: The current value to process
  • index: The index in the iterable. Will start from 0.
  • iterable: The iterable on which the operation is being performed.
Source:
Returns:

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
Example
import { every, asyncRoot, sleep } from 'modern-async'

asyncRoot(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, concurrency) → {Promise}

Returns true if all elements of an iterable pass a truth test and false otherwise.

The iteratee will be run in parallel, up to a concurrency limit. 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.

Parameters:
Name Type Description
iterable Iterable

An iterable object.

iteratee function

A function that will be called with each member of the iterable. It will receive three arguments:

  • value: The current value to process
  • index: The index in the iterable. Will start from 0.
  • iterable: The iterable on which the operation is being performed.
concurrency number

The number of times iteratee can be called concurrently.

Returns:

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
Example
import { everyLimit, asyncRoot, sleep } from 'modern-async'

asyncRoot(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}

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.

Parameters:
Name Type Description
iterable Iterable

An iterable object.

iteratee function

A function that will be called with each member of the iterable. It will receive three arguments:

  • value: The current value to process
  • index: The index in the iterable. Will start from 0.
  • iterable: The iterable on which the operation is being performed.
Returns:

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
Example
import { everySeries, asyncRoot, sleep } from 'modern-async'

asyncRoot(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}

Returns a new array of all the values in iterable which pass an asynchronous truth test.

The calls to iteratee will perform in parallel, but the results array will be in the same order than the original.

If any of the calls to iteratee throws an exception the returned promised will be rejected.

Parameters:
Name Type Description
iterable Iterable

An iterable object.

iteratee function

A function that will be called with each member of iterable. It will receive three arguments:

  • value: The current value to process
  • index: The index in the iterable. Will start from 0.
  • iterable: The iterable on which the operation is being performed.
Source:
Returns:

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
Example
import { filter, asyncRoot, sleep } from 'modern-async'

asyncRoot(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) filterLimit(iterable, iteratee, concurrency) → {Promise}

Returns a new array of all the values in iterable which pass an asynchronous truth test.

The calls to iteratee will perform in parallel, up to the concurrency limit, but the results array will be in the same order than the original.

If any of the calls to iteratee throws an exception the returned promised will be rejected and the remaining pending tasks will be cancelled.

Parameters:
Name Type Description
iterable Iterable

An iterable object.

iteratee function

A function that will be called with each member of iterable. It will receive three arguments:

  • value: The current value to process
  • index: The index in the iterable. Will start from 0.
  • iterable: The iterable on which the operation is being performed.
concurrency number

The number of times iteratee can be called concurrently.

Returns:

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
Example
import { filterLimit, asyncRoot, sleep } from 'modern-async'

asyncRoot(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}

Returns a new array of all the values in iterable which pass an asynchronous truth test.

The calls to iteratee will perform sequentially and the results array will be in the same order than the original.

If any of the calls to iteratee throws an exception the returned promised will be rejected and the remaining pending tasks will be cancelled.

Parameters:
Name Type Description
iterable Iterable

An iterable object.

iteratee function

A function that will be called with each member of the iterable. It will receive three arguments:

  • value: The current value to process
  • index: The index in the iterable. Will start from 0.
  • iterable: The iterable on which the operation is being performed.
Returns:

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
Example
import { filterSeries, asyncRoot, sleep } from 'modern-async'

asyncRoot(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) → {Promise}

Returns the first element of an iterable that passes an asynchronous truth test.

The calls to iteratee will run in parallel. This implies that the element found by this function may not be the first element of the iterable able to pass the truth test. It will be the first one in time for which one of the parallel calls to iteratee was able to return a positive result. If you need a sequential alternative use findSeries().

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.

Parameters:
Name Type Description
iterable Iterable

An iterable object.

iteratee function

A function that will be called with each member of the iterable. It will receive three arguments:

  • value: The current value to process
  • index: The index in the iterable. Will start from 0.
  • iterable: The iterable on which the operation is being performed.
Source:
Returns:

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
Example
import { find, asyncRoot, sleep } from 'modern-async'

asyncRoot(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 or 3 randomly
})

# (async) findIndex(iterable, iteratee) → {Promise}

Returns the index of the first element of an iterable that passes an asynchronous truth test.

The calls to iteratee will run in parallel. This implies that the element found by this function may not be the first element of the iterable able to pass the truth test. It will be the first one in time for which one of the parallel calls to iteratee was able to return a positive result. If you need a sequential alternative use findIndexSeries().

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.

Parameters:
Name Type Description
iterable Iterable

An iterable object.

iteratee function

A function that will be called with each member of the iterable. It will receive three arguments:

  • value: The current value to process
  • index: The index in the iterable. Will start from 0.
  • iterable: The iterable on which the operation is being performed.
Returns:

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
Example
import { findIndex, asyncRoot, sleep } from 'modern-async'

asyncRoot(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 or 2 randomly
})

# (async) findIndexLimit(iterable, iteratee, concurrency) → {Promise}

Returns the index of the first element of an iterable that passes an asynchronous truth test.

The calls to iteratee will run in parallel, up to a concurrency limit. This implies that the element found by this function may not be the first element of the iterable able to pass the truth test. It will be the first one in time for which one of the parallel calls to iteratee was able to return a positive result. If you need a sequential alternative use findIndexSeries().

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.

Parameters:
Name Type Description
iterable Iterable

An iterable object.

iteratee function

A function that will be called with each member of the iterable. It will receive three arguments:

  • value: The current value to process
  • index: The index in the iterable. Will start from 0.
  • iterable: The iterable on which the operation is being performed.
concurrency number

The number of times iteratee can be called concurrently.

Returns:

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
Example
import { findIndexLimit, asyncRoot, sleep } from 'modern-async'

asyncRoot(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, 2 or 4 randomly
  // 4 is a potential result in this case even with a concurrency of 3 due to how
  // randomness works, and all asynchronous operations are inherently random. The only way to ensure an
  // order is to use a concurreny of 1 or to use findSeries() which does the same thing.
})

# (async) findIndexSeries(iterable, iteratee) → {Promise}

Returns the index of the first element of an iterable that passes an asynchronous truth test.

The calls to iteratee will run sequentially. As opposed to findIndex() and findIndexLimit() this ensures that if multiple values may pass the truth test it will be the first one of the iterable that will be returned.

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.

Parameters:
Name Type Description
iterable Iterable

An iterable object.

iteratee function

A function that will be called with each member of the iterable. It will receive three arguments:

  • value: The current value to process
  • index: The index in the iterable. Will start from 0.
  • iterable: The iterable on which the operation is being performed.
Returns:

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
Example
import { findIndexSeries, asyncRoot, sleep } from 'modern-async'

asyncRoot(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) // always prints 0
})

# (async) findLimit(iterable, iteratee, concurrency) → {Promise}

Returns the first element of an iterable that passes an asynchronous truth test.

The calls to iteratee will run in parallel, up to a concurrency limit. This implies that the element found by this function may not be the first element of the iterable able to pass the truth test. It will be the first one for which one of the parallel calls to iteratee was able to return a positive result. If you need a sequential alternative use findSeries().

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.

Parameters:
Name Type Description
iterable Iterable

An iterable object.

iteratee function

A function that will be called with each member of the iterable. It will receive three arguments:

  • value: The current value to process
  • index: The index in the iterable. Will start from 0.
  • iterable: The iterable on which the operation is being performed.
concurrency number

The number of times iteratee can be called concurrently.

Returns:

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
Example
import { findLimit, asyncRoot, sleep } from 'modern-async'

asyncRoot(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, 3 or 5 randomly
  // 5 is a potential result in this case even with a concurrency of 3 due to how
  // randomness works, and all asynchronous operations are inherently random. The only way to ensure an
  // order is to use a concurreny of 1 or to use findSeries() which does the same thing.
})

# (async) findSeries(iterable, iteratee) → {Promise}

Returns the first element of an iterable that passes an asynchronous truth test.

The calls to iteratee will run sequentially. As opposed to find() and findLimit() this ensures that if multiple values may pass the truth test it will be the first one of the iterable that will be returned.

In case of exception in one of the iteratee calls the promise returned by this function will be rejected with the exception.

Parameters:
Name Type Description
iterable Iterable

An iterable object.

iteratee function

A function that will be called with each member of the iterable. It will receive three arguments:

  • value: The current value to process
  • index: The index in the iterable. Will start from 0.
  • iterable: The iterable on which the operation is being performed.
Returns:

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
Example
import { findSeries, asyncRoot, sleep } from 'modern-async'

asyncRoot(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) // always 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 promised will be rejected.

Parameters:
Name Type Description
iterable Iterable

An iterable object.

iteratee function

A function that will be called with each member of the iterable. It will receive three arguments:

  • value: The current value to process
  • index: The index in the iterable. Will start from 0.
  • iterable: The iterable on which the operation is being performed.
Source:
Returns:

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
Example
import { forEach, asyncRoot, sleep } from 'modern-async'

asyncRoot(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, concurrency) → {Promise}

Calls a function on each element of iterable.

Multiple calls to iteratee will be performed in parallel, up to the concurrency limit.

If any of the calls to iteratee throws an exception the returned promised will be rejected and the remaining pending tasks will be cancelled.

Parameters:
Name Type Description
iterable Iterable

An iterable object.

iteratee function

A function that will be called with each member of the iterable. It will receive three arguments:

  • value: The current value to process
  • index: The index in the iterable. Will start from 0.
  • iterable: The iterable on which the operation is being performed.
concurrency number

The number of times iteratee can be called concurrently.

Returns:

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
Example
import { forEachLimit, asyncRoot, sleep } from 'modern-async'

asyncRoot(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 promised will be rejected and the remaining pending tasks will be cancelled.

Parameters:
Name Type Description
iterable Iterable

An iterable object.

iteratee function

A function that will be called with each member of the iterable. It will receive three arguments:

  • value: The current value to process
  • index: The index in the iterable. Will start from 0.
  • iterable: The iterable on which the operation is being performed.
Returns:

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
Example
import { forEachSeries, asyncRoot, sleep } from 'modern-async'

asyncRoot(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}

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 promised will be rejected.

Parameters:
Name Type Description
iterable Iterable

An iterable object.

iteratee function

A function that will be called with each member of the iterable. It will receive three arguments:

  • value: The current value to process
  • index: The index in the iterable. Will start from 0.
  • iterable: The iterable on which the operation is being performed.
Source:
Returns:

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
Example
import { map, asyncRoot, sleep } from 'modern-async'

asyncRoot(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) mapLimit(iterable, iteratee, concurrency) → {Promise}

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, up to the concurrency limit.

If any of the calls to iteratee throws an exception the returned promised will be rejected and the remaining pending tasks will be cancelled.

Parameters:
Name Type Description
iterable Iterable

An iterable object.

iteratee function

A function that will be called with each member of the iterable. It will receive three arguments:

  • value: The current value to process
  • index: The index in the iterable. Will start from 0.
  • iterable: The iterable on which the operation is being performed.
concurrency number

The number of times iteratee can be called concurrently.

Returns:

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
Example
import { mapLimit, asyncRoot, sleep } from 'modern-async'

asyncRoot(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}

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 promised will be rejected and the remaining pending tasks will be cancelled.

Parameters:
Name Type Description
iterable Iterable

An iterable object.

iteratee function

A function that will be called with each member of the iterable. It will receive three arguments:

  • value: The current value to process
  • index: The index in the iterable. Will start from 0.
  • iterable: The iterable on which the operation is being performed.
Returns:

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
Example
import { mapSeries, asyncRoot, sleep } from 'modern-async'

asyncRoot(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
})

# (async) reduce(iterable, reducer, initial) → {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.

Parameters:
Name Type Description
iterable Iterable

An iterable object.

reducer function

The reducer function. It will be called with four arguments:

  • accumulator: The last calculated value (or the first value of the iterable if no initial value is provided)
  • value: The current value
  • index: The current index in the iterable. Will start from 0 if no initial value is provided, 1 otherwise.
  • iterable: The iterable on which the reduce operation is performed.
initial *

The initial value that will be used as accumulator in the first call to reducer. If omitted the first element of iterable will be used as accumulator and reducer will only be called from from the second element of the list (as defined in the Array.reduce() function).

Source:
Returns:

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
Example
import { reduce, asyncRoot, sleep } from 'modern-async'

asyncRoot(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, initial) → {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.

Parameters:
Name Type Description
iterable Iterable

An iterable object.

reducer function

The reducer function. It will be called with four arguments:

  • accumulator: The last calculated value (or the first value of the iterable if no initial value is provided)
  • value: The current value
  • index: The current index in the iterable. Will start from the last index if no initial value is provided, the last index minus 1 otherwise.
  • iterable: The iterable on which the reduce operation is performed.
initial *

The initial value that will be used as accumulator in the first call to reducer. If omitted the first element of iterable will be used as accumulator and reducer will only be called from from the second element of the list (as defined in the Array.reduce() function).

Returns:

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
Example
import { reduceRight, asyncRoot, sleep } from 'modern-async'

asyncRoot(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}

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.

Parameters:
Name Type Description
amount number

An amount of time in milliseconds

Source:
Returns:

A promise that will be resolved after the given amount of time has passed.

Type
Promise
Examples
import { sleep, asyncRoot } from 'modern-async'

asyncRoot(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.

Parameters:
Name Type Description
amount number

An amount of time in milliseconds

Returns:

A tuple of two objects:

  • promise: The promise
  • cancel: The cancel function. It will return a boolean that will be true if the promise was effectively cancelled, false otherwise.
Type
Array
Example
import { sleepCancellable, asyncRoot } from 'modern-async'

asyncRoot(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}

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.

Parameters:
Name Type Description
amount number

An amount of time in milliseconds

Returns:

A promise that will be resolved after the given amount of time has passed.

Type
Promise
Example
import { sleepPrecise, asyncRoot } from 'modern-async'

asyncRoot(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.

Parameters:
Name Type Description
amount number

An amount of time in milliseconds

Returns:

A tuple of two objects:

  • promise: The promise
  • cancel: The cancel function. It will return a boolean that will be true if the promise was effectively cancelled, false otherwise.
Type
Array
Example
import { sleepPreciseCancellable, asyncRoot } from 'modern-async'

asyncRoot(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}

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.

Parameters:
Name Type Description
iterable Iterable

An iterable object.

iteratee function

A function that will be called with each member of the iterable. It will receive three arguments:

  • value: The current value to process
  • index: The index in the iterable. Will start from 0.
  • iterable: The iterable on which the operation is being performed.
Source:
Returns:

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
Example
import { some, asyncRoot, sleep } from 'modern-async'

asyncRoot(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, concurrency) → {Promise}

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, up to a concurrency limit. 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.

Parameters:
Name Type Description
iterable Iterable

An iterable object.

iteratee function

A function that will be called with each member of the iterable. It will receive three arguments:

  • value: The current value to process
  • index: The index in the iterable. Will start from 0.
  • iterable: The iterable on which the operation is being performed.
concurrency number

The number of times iteratee can be called concurrently.

Returns:

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
Example
import { someLimit, asyncRoot, sleep } from 'modern-async'

asyncRoot(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}

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.

Parameters:
Name Type Description
iterable Iterable

An iterable object.

iteratee function

A function that will be called with each member of the iterable. It will receive three arguments:

  • value: The current value to process
  • index: The index in the iterable. Will start from 0.
  • iterable: The iterable on which the operation is being performed.
Returns:

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
Example
import { someSeries, asyncRoot, sleep } from 'modern-async'

asyncRoot(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.

Parameters:
Name Type Description
fct function

An asynchronous function that will be called immediately without arguments.

amount number

An amount of time in milliseconds

Source:
Returns:

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
Example
import { timeout, sleep, asyncRoot } from 'modern-async'

asyncRoot(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.

Parameters:
Name Type Description
fct function

An asynchronous function that will be called immediately without arguments.

amount number

An amount of time in milliseconds

Returns:

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
Example
import { timeoutPrecise, sleep, asyncRoot } from 'modern-async'

asyncRoot(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
  }
})