p-iteration icon indicating copy to clipboard operation
p-iteration copied to clipboard

Is it possible to use in a chain?

Open lmcarreiro opened this issue 5 years ago • 1 comments

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?

lmcarreiro avatar Sep 18 '19 14:09 lmcarreiro

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)));

toniov avatar Oct 04 '19 11:10 toniov