javascript - How do I reduce multiple Promise.all?

早过忘川 提交于 2019-12-12 01:57:31

问题


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?


回答1:


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



回答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)
    ]);
  }));
});


来源:https://stackoverflow.com/questions/43433643/javascript-how-do-i-reduce-multiple-promise-all

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!