1

I am having an issue returning data from an async function it seems that await doesn't work.

I have this function below which return some data that i push inside "reminders" array and return it.

getReminderData = async () => {
// Firestore data converter
const user = await UserRepository.getUserRef(
  firebase.auth().currentUser.uid
);
let reminders = [];
const remindersRecord = await firebase
  .firestore()
  .collection("reminder")
  .withConverter(ReminderConverter.getReminderConverter())
  .where("user", "==", user)
  .get();

remindersRecord.forEach(async (reminderDoc) => {
  const data = await reminderDoc.data();
  reminders.push(data);
  console.log(reminders);
});
return reminders;

};

Then I have

async componentDidMount() {
  let remindersData = await this.getReminderData();
  console.log(remindersData);

}

the problem here is that console.log(remindersData) doesn't show the data which is normal since this console log is fired before the completion of getReminderData() as if the await didn't wait.

Could you help me find out what did i do wrong?

Thanks in advance for your help !

1 Answer 1

0

Your function will return reminders without waiting

remindersRecord.forEach(async (reminderDoc) => {
  const data = await reminderDoc.data();
  reminders.push(data);
  console.log(reminders);
});

The forEach create new scope and the outer scope will not wait for it. Instead, try this

getReminderData = async () => {
  // Firestore data converter
  const user = await UserRepository.getUserRef(
    firebase.auth().currentUser.uid
  );
  const remindersRecord = await firebase
    .firestore()
    .collection("reminder")
    .withConverter(ReminderConverter.getReminderConverter())
    .where("user", "==", user)
    .get();

  return remindersRecord.map(reminder => reminder.data())
};


Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.