How to aggregate 2d array Promises?

Viewed 138

I am trying to resolve an 2d dimension of array of promises but i am unable to resolve it and it shows in pending states after I used Promise.All.
Can anyone suggest me how to solve this problem?

Here is the getAuth function I am using to get the users info:

const getAuth = async(phoneNumber) => {
   return db.getUserByPhoneNumber(phoneNumber).catch((error) => {
        // console.log(error)
        return {
          phoneNumber,
          uid: null,
          email: "",
          displayName: "",
          emailVerified: false,
          disabled: false,
        };
   });
};

and using that I am trying to solve an array of phoneNumbers but after resolving the arrays it still shows the pending states:

const x = async() => {
   const xy = [
        ["+9188", "+9199"],
        ["+9188", "+9199", "+9188"],
   ];
   const p = [];
   xy.forEach((doc) => {
      p.push(doc.map(getAuth));
   });
   console.log(p, "P");
   const [users] = await Promise.all([Promise.all(p)]);
   console.log(users, "users");
};
x();

Here is the output I am getting:

    [ [ Promise { <pending> }, Promise { <pending> } ],
      [ Promise { <pending> },
        Promise { <pending> },
        Promise { <pending> } ] ] 'P'
    [ [ Promise { <pending> }, Promise { <pending> } ],
      [ Promise { <pending> },
        Promise { <pending> },
        Promise { <pending> } ] ] 'users'
1 Answers

Use nested Array.map(), and Promise.all() combination to wait for each level of the array to resolve:

const getAuth = phoneNumber => Promise.resolve(`resolved-${phoneNumber}`);

const x = phoneNumbers =>
  // map and wait for each sub-array to resolve
  Promise.all(phoneNumbers.map(nums =>
    // map and wait for each getAuth to resolve
    Promise.all(nums.map(getAuth)) 
  ))
  
const phoneNumbers = [
  ["+9188", "+9199"],
  ["+9188", "+9199", "+9188"],
];

x(phoneNumbers)
  .then(console.log)

Related