Javascript - How Do I Reduce Multiple Promise.all?
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.
Solution 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()
.
returnUserQueries.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());
})
Solution 2:
There's no need to use reduce()
. Just map the things and wait them all.
returnUserQueries.addUsersOnCasefileCreate(input).then(users => {
returnPromise.all(users.map((user) => {
returnPromise.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)
]);
}));
});
Post a Comment for "Javascript - How Do I Reduce Multiple Promise.all?"