0

I am trying to use a Promise.all inside of a reduce and cannot get my function to work, unless there is only one user in my array. The starting object of the reduce is a Promise. The first time through the reduce, the Promise has .all available on it. The second time through, the .all is not available.

return UserQueries.addUsersOnCasefileCreate(input).then(users => {
  return users.reduce((promise, user) => {
    return promise.all([
      AddressQueries.addAddress(user.address, user.userId, input.orgId),
      EmailQueries.addEmail(user.emails, user.userId, input.orgId),
      PhoneQueries.addPhones(user.phones, user.userId, input.orgId)
    ])
    .then(() => Promise.resolve(user))
  }, Promise);
})

How could I perform this operation?

jhamm
  • 24,124
  • 39
  • 105
  • 179

2 Answers2

3

You initialize with Promise which is a function, though return a resolved Promise object, where the two are not the same.

You can initialize with Promise.resolve(), call promise.then(), then return Promise.all() with .then() chained within first .then(), which passes Promise object to next iteration at .reduce().

return UserQueries.addUsersOnCasefileCreate(input).then(users => {
  return users.reduce((promise, user) => {
    return promise.then(() => Promise.all([
      AddressQueries.addAddress(user.address, user.userId, input.orgId),
      EmailQueries.addEmail(user.emails, user.userId, input.orgId),
      PhoneQueries.addPhones(user.phones, user.userId, input.orgId)
    ]))
    .then(() => user))
  }, Promise.resolve());
})
guest271314
  • 1
  • 15
  • 104
  • 177
  • I tried this, but I only get the last user in the result. I don't get the rest of the users that are inserted. – jhamm Apr 16 '17 at 04:53
  • What do you mean by "I don't get the rest of the users that are inserted."? There is no need to use `.reduce()` if expected result is array of results. What is purpose for using `.reduce()`? – guest271314 Apr 16 '17 at 04:54
2

There's no need to use reduce(). Just map the things and wait them all.

return UserQueries.addUsersOnCasefileCreate(input).then(users => {
  return Promise.all(users.map((user) => {
    return Promise.all([
      AddressQueries.addAddress(user.address, user.userId, input.orgId),
      EmailQueries.addEmail(user.emails, user.userId, input.orgId),
      PhoneQueries.addPhones(user.phones, user.userId, input.orgId)
    ]);
  }));
});
Tatsuyuki Ishi
  • 3,883
  • 3
  • 29
  • 41