0

I have two Promises (let's say p and q) that will retrieve data when resolved, and I want to do something foo that needs the both data. It has a solution as coded below. But is there a more elegant one?

p.then(pData => {
  q.then(qData => {
    foo(pData,qData);
  });
});

I was wondering something like follows (hypothetical function and):

p.and(q).then(dataArr => foo( ...dataArr ));

In the case there's no such way, is there anything in the promises concept that would disallow this construction?

LBald
  • 393
  • 1
  • 10
  • 6
    `Promise.all([p, q]).then` is your friend... – trincot Oct 09 '20 at 18:36
  • `Promise.all([p, q]).then(dataArr => foo(...dataArr));` Docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all – Rocket Hazmat Oct 09 '20 at 18:40
  • 1
    Promise.all or async...await. – Bulent Oct 09 '20 at 18:41
  • @Bergi, that is a strange dupe reference... "How do I access previous promise results in a .then() chain?" .... is nothing like the question here? What was wrong with my initial dupe reference? – trincot Oct 09 '20 at 18:55
  • 1
    @trincot The original dupe target felt strange to me because the OP has no loop here… But you're right, the "accesss previous results" one doesn't fit well either since the promises don't need to be chained here. I guess we have no good canonical here? [This one](https://stackoverflow.com/q/46889290/1048572) uses `await`, [this one](https://stackoverflow.com/q/21759361/1048572) is `$q`-specific, maybe [that one](https://stackoverflow.com/q/37841721/1048572)? – Bergi Oct 09 '20 at 19:09
  • Yes, last one is good. I removed "Angular" from its title. – trincot Oct 09 '20 at 19:22

0 Answers0