1

I have some promises, for example:

promise1 = function() { return new Promise(a,b){} ....}

promise2 = function() { return new Promise(a,b){} ....}

promise3 = function() { return new Promise(a,b){} ....}

promise4 = function() { return new Promise(a,b){} ....}

It is possible to create other Promises by nesting these promises (1,2,3,4), for example:

promiseX = function() {

     return new Promise(function() {

         promise1().then(promise2)...          

     })

 }

 promiseY = function() {

     return new Promise(function() {

         promise3().then(promise4).....        

     })

 }

To then use the last two created:

promiseX().then(promiseY).then(function().....)

Is this correct to do? What would be the correct way to do it in any case?

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Iventura
  • 11
  • 3
  • take a look at [async.waterfall](https://caolan.github.io/async/v3/docs.html#waterfall) – Samuel Goldenbaum Jun 09 '20 at 19:18
  • 1
    Avoid the [`Promise` constructor antipattern](https://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-it) - [the `then` method already takes care of the nesting](https://stackoverflow.com/a/22562045/1048572) – Bergi Jun 09 '20 at 19:25

2 Answers2

1

First, to be pedantic, promise1 through promise4 aren't actually promises; they're functions that return Promises. Yes, it's possible, to create a new function that sequences the Promises from the other two functions:

const promiseX = () => promise1().then(promise2)
const promiseY = () => promise3().then(promise4)

promiseX().then(promiseY).then(() => { /* ... */ })
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Jacob
  • 77,566
  • 24
  • 149
  • 228
-1

If you want the promises to resolve in sequence, just say (using your example functions):

promise1()
.then( promise2() )
.then( promise3() )
.then( promise4() )
;

In this example, do not that each of the promiseX() functions will receive the resolved value of the previous promise, rather as is you had written this:

promise1()
.then( res => promise2( res ) )
.then( res => promise3( res ) )
.then( res => promise4( res ) )
;

And in both cases, the resolved value of the entire promise chain will be the resolved value of the last promise (promise4).

If you want them all to resolve, but don't care about the order, then something like this:

Promise.all([
  promise1(),
  promise2(),
  promise3(),
  promise4()
]);

will do you. Do note, however, that both of the above examples will reject if any of the promises reject. And the resolved value will be an array of the resolved values of all the promises: [ v1, v2 v3, v4 ].

Nicholas Carey
  • 71,308
  • 16
  • 93
  • 135