0

I expect to push element in array but when I log, the array is empty how to solve that this is the code please help

let recipient = [] // this is the array
  student.legalGuardians.map(async (legalGuardians) => {
    let user = await getUserByNationalIdOrPhoneNumberOrEmail(
      legalGuardians.nationalId,
      legalGuardians.phoneNumber,
      legalGuardians.email
    );
    if (!user || user == false) {
      return;
    }
    if (user.firebaseToken != null || user.firebaseToken != undefined) {
      Notifystatus = await sendNotificationforUser(
        subject,
        body,`
        `data,
        user.firebaseToken
      );
    }
    recipient.push({
      userId: user._id,
      Notifystatus: Notifystatus,
      studentId: student._id,
    });
    console.log(recipient);
  });
console.log(recipient)
// output []
Konrad
  • 21,590
  • 4
  • 28
  • 64
  • Does this answer your question? [Use async await with Array.map](https://stackoverflow.com/questions/40140149/use-async-await-with-array-map) – Konrad Mar 14 '23 at 08:45
  • Does this answer your question? [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – jabaa Mar 14 '23 at 08:46
  • 1
    Unrelated: Don't use `map` when you discard the returned array. Use `forEach` instead. But in this case, you should store the array of promises and await them. – jabaa Mar 14 '23 at 08:47

1 Answers1

1

You need to wait until all your awaits have resolved. You can filter the empty results afterwards:

const promises = student.legalGuardians.map(async(legalGuardians) => {
  let user = await getUserByNationalIdOrPhoneNumberOrEmail(...);
  if (!user || user == false) {
    return undefined;
  }
  if (user.firebaseToken != null || user.firebaseToken != undefined) {
    ...
  }
  return {
    userId: user._id,
    Notifystatus: Notifystatus,
    studentId: student._id,
  };
});
const recipient = (await Promise.all(promises)).filter(Boolean)

Here is a dummy example if it helps:

const student = [{ legalGuardian: null, _id: 1 }, { legalGuardian: null, _id: 2 }, { legalGuardian: null, _id: 3 }]

const loadUserIfIdIsOdd = (student) => new Promise(resolve => resolve(student._id % 2 === 1 ? { _id: student._id } : null))

const promises = student.map(async (student) => {
  let user = await loadUserIfIdIsOdd(student);
  if (!user) {
    return undefined;
  }

  return {
    userId: user._id,
    studentId: student._id,
  };
});

(async function () {
  const recipient = (await Promise.all(promises)).filter(Boolean)
  console.log(JSON.stringify(recipient))
})()
Moritz Ringler
  • 9,772
  • 9
  • 21
  • 34