Skip to content

parallel

Run many async function in parallel

1272 bytes

Usage

Like _.map but built specifically to run the async callback functions in parallel. The first argument is a limit of how many functions should be allowed to run at once. Returns an array of results.

import * as _ from 'radashi'
const userIds = [1, 2, 3, 4, 5, 6, 7, 8, 9]
// Will run the find user async function 3 at a time
// starting another request when one of the 3 is freed
const users = await _.parallel(3, userIds, async userId => {
return await api.users.find(userId)
})

Errors

When all work is complete parallel will check for errors. If any occurred they will all be thrown in a single AggregateError that has an errors property that is all the errors that were thrown.

import * as _ from 'radashi'
const userIds = [1, 2, 3]
const [err, users] = await _.tryit(_.parallel)(3, userIds, async userId => {
throw new Error(`No, I don\'t want to find user ${userId}`)
})
console.log(err) // => AggregateError
console.log(err.errors) // => [Error, Error, Error]
console.log(err.errors[1].message) // => No, I don't want to find user 2