Rigid Studios
Rigid Studios

Reputation: 195

How can I wait for 2 promises to complete, to run another?

I'm trying to run two promises with:

Promise.all([...])

But they both have their own .then:

Promise.all([promise1().then(...), promise2().then(...)])

And I wish to run another .then on the Promise.all, while also waiting for both .then to return if that makes any sense.

Here's a fiddle showing what I mean.

Upvotes: 1

Views: 71

Answers (2)

Lajos Arpad
Lajos Arpad

Reputation: 76508

If you run

function get1() {
  return new Promise((r)=>setTimeout(() => r(),3000))
}

function rejection() {/*Handle rejection*/}

function doAll(...ps) {
    return Promise.all(ps.map(rejection))
}

(async () => {
  var p1 = get1().then(()=>console.log("1"));
  var p2 = get1().then(()=>console.log("2"));
    Promise.all([p1, p2]).then(()=>{
    console.log("3")
  })
})()

then the result is the correct

1

2

3

If you run

function get1() {
  return new Promise((r)=>setTimeout(() => r(),3000))
}

function rejection() {/*Handle rejection*/}

function doAll(...ps) {
    return Promise.all(ps)
}

(async () => {
  var p1 = get1().then(()=>console.log("1"));
  var p2 = get1().then(()=>console.log("2"));
    doAll(p1, p2).then(()=>{
    console.log("3")
  })
})()

then you again get the correct

1

2

3

As a result, the problem is with the part of ps.map(rejection). Let's see:

function get1() {
  return new Promise((r)=>setTimeout(() => r(),3000))
}

function rejection() {/*Handle rejection*/}

function doAll(...ps) {
    console.log(ps);
  console.log(ps.map(rejection));
    return Promise.all(ps.map(rejection));
}

(async () => {
  var p1 = get1().then(()=>console.log("1"));
  var p2 = get1().then(()=>console.log("2"));
    doAll(p1, p2).then(()=>{
    console.log("3")
  })
})()

Output

enter image description here

The array of two elements, both being undefined is trivial to evaluate. Because ps.map(rejection) is an arrow function that names its parameter rejection and does not return anything.

Upvotes: 1

Seyed-Amir-Mehrizi
Seyed-Amir-Mehrizi

Reputation: 739

if you want to work with async operation in javascript, there are 3 ways that you can use.

  1. callback
  2. Promise
  3. async/await

In order to implement the exact thing that you want, the best and the optimized way is using the async/await method.

you can do it like this :

      async function getAllData(){

      const p1 = await promise1;
      const p2 = await promise2;
       
      }

now getAllData return Promise, you can use .then() to get the result and .catch() to get errors.

to read more about syntax and other features you can go to this site : explain about async and await

Upvotes: 0

Related Questions