kittu
kittu

Reputation: 7008

How to return array of promises inside map in javascript

function handler(){
    const results = [].map((item) => {
      a();
      b();
    })
    Promise.allSettled(results);
  }

  function a() {
    // returns promise
  }
  function b() {
    // returns promise
  }
}

How to modify the above code so that I can pass array of promises to promise.allSettled(results)

I tried this but not sure if this is correct way?

function handler() {
    const results = [].map((item) => {
      const out1 = a();
      const out2 = b();
      return [...out1, ...out2];
    })
    Promise.allSettled(results);
}

Upvotes: 1

Views: 266

Answers (2)

epascarello
epascarello

Reputation: 207501

Use flatMap

const a = [1,2,3,4,5,6];

const b = a.flatMap(v => [Promise.resolve(a), Promise.reject(a)])

Promise.allSettled(b).then(x => console.log(x));

Upvotes: 1

codinn.dev
codinn.dev

Reputation: 260

This should work

function handler() {
    const results = [].map((item) => {
      const out1 = a();
      const out2 = b();
      return [...out1, ...out2];
    })
    Promise.allSettled(results.flat());
}

Upvotes: 0

Related Questions