toniov / p-iteration

Utilities that make array iteration easy when using async/await or Promises
https://toniov.github.io/p-iteration
352 stars 19 forks source link

Is it possible to use in a chain? #15

Open lmcarreiro opened 5 years ago

lmcarreiro commented 5 years ago

It is common in libraries like this, to have a chain method, to allow you to use the methods in a chain without aux variables or putting one call inside the other.

Example:

const { chain } = require('p-iteration');

const usersIds = [1, 2, 3];
const users = await chain(usersIds)
  .map(async id => await getById(id))
  .filter(async user => await checkIsActive(user.anotherId))
  .value()

Is it possible to use an async chain?

toniov commented 5 years ago

Hey sorry for the late reply!

Currently that's not possible, but it could be a good idea for a new version of the module.

Anyway, since each method returns a Promise you can chain them like you'd do normally, using your example:

const { map, filter } = require('p-iteration');

const usersIds = [1, 2, 3];
const users = await map(usersIds, user => usergetById(id))
  .then(users => filter(users,  user => checkIsActive(user.anotherId)));

It's not so smooth though, for this case just going with sequential awaits is a bit simpler I think:

const users = await map(usersIds, user => usergetById(id));
const filteredUsers = await filter(users,  user => checkIsActive(user.anotherId)));