Home > Software design >  How to return Return Promise from Array.reduce
How to return Return Promise from Array.reduce

Time:11-08

I am iterating over an array of objects using Array.reduce and trying to return promise from there. I making some modifications inside the reduce method and after the promise resolved reviewCards['departments'] key within the object has the modified data but reviewCards['genders'] is empty. I think all the promises are not resolving properly.

How I can return the final Object as Promise?

public getCompanyReviewCards(
   reviewGroups: ICompanyReviewGroups,
   reviews: CompanyReview[],
): Promise<[key: string]: ICompanyReviewCard> {
  
   return new Promise((resolve, reject) => { 
      const reviewCards = Object.keys(reviewGroups).reduce(
         async (reviewCards: ICompanyReviewCards, groupKey: string) => {

            const group = reviewGroups[groupKey];
            reviewCards['genders'] = reviewCards['genders'] || [];
            reviewCards['departments'] = reviewCards['departments'] || [];

            //Department wise cards
            //This block is excuting properyly
            if (groupKey === '_departmentGroup') {
                 const departmentsCards = await this.getCardsByDepartments(group);
                 reviewCards['departments'] = departmentsCards;
            }

            //Gender wise cards
            //This block is not excuting properyly
            if (groupKey === '_genderGroup') {
                 const gendersCards = await this.getCardsByGender(group);
                 reviewCards['genders'] = gendersCards;
            }

            return reviewCards;

         },Object.create(null),
      );

   resolve(reviewCards);

   })
}

CodePudding user response:

reduce isn't promise aware and won't handle your promises automatically, so you have to do it yourself. Keep in mind that the first argument to the callback is the value returned from the previous iteration which will be a promise.

const main = async() => {
  const generateNumber = () => {
    return new Promise(resolve => setTimeout(() => resolve(Math.random()), 1000));
  };

  const data = ['a', 'b', 'c'];
  const promiseReducedData = data.reduce(async(previousValuePromise, currentValue, index) => {
    const resolvedPreviousValue = await previousValuePromise;
    console.log(`Working on index ${index}`);
    const newValue = {
      ...resolvedPreviousValue,
      [currentValue]: await generateNumber()
    };
    return newValue;
  }, {});
  const reducedData = await promiseReducedData;
  console.log(reducedData);
};

main();

CodePudding user response:

ich you return a promise, you got to await it, too: `await reviewCards"

  • Related