0

When I print the length of the array it is 3, so basically arr[0], arr[1], arr[2] contain same objects, why is that so The array returned should be of length 1 containing all the objects.

const arr = await Promise.all(
          ratingsArr.map(async (rating) => {
            const pmRatingObj = {
              rateeId: rating.employeeId,
              createdAt: rating.createdAt,
              updatedAt: rating.updatedAt,
              rateeType: 'employee',
              raterId: rating.projectManagerId,
              freeze: rating.PMFreeze,
            };
            const pmRatingId = await queryInterface.bulkInsert('ratings', [pmRatingObj]);
            // console.log(pmRatingId);
    
            const archRatingObj = {
              rateeId: rating.employeeId,
              createdAt: rating.createdAt,
              updatedAt: rating.updatedAt,
              rateeType: 'employee',
              raterId: rating.projectArchitectId,
              freeze: rating.PMFreeze,
            };
            const archRatingId = await queryInterface.bulkInsert('ratings', [archRatingObj]);
    
            const pmArr = await createPMAttributes(pmRatingId, rating);
            pmArr.map((pm) => {
              newArr.push(pm);
            });
            const archArr = await createArchAttributes(archRatingId, rating);
            archArr.map((arch) => {
              newArr.push(arch);
            });
    
            return newArr;
    
            
          }),
        );
habiba
  • 321
  • 3
  • 12
  • 3
    You are returning `newArr` from the inner Promise, so you'll get `[newArr, newArr, newArr]` as result of `Promise.all`. Note that pushing to an array, especially inside a Promise, usually means you're doing it wrong. You also shouldn't use `.map` as a shortcut for `.forEach`. The whole point of `.map` is to build a new array from an existing one, and you're pushing to a new array instead, creating part of the problem in the process. –  May 31 '21 at 07:55
  • can you please refactor my code, so that I get only one array with all the objects. Im new to Javascript promises, would really appreciate it! – habiba May 31 '21 at 07:57
  • 1
    Here's the basic idea: https://jsfiddle.net/ov7byczL/ –  May 31 '21 at 08:05
  • thanks a lot! :) that really made things clear :D – habiba May 31 '21 at 08:14

0 Answers0